You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改win32com代码添加并选择Outlook第二个邮箱?

切换到第二个Outlook账户处理附件的修改方案

原代码里mapi.GetDefaultFolder(6)默认调用的是Outlook中设置的默认账户(第一个账户)的收件箱。要切换到第二个账户,只需要先获取所有账户列表,再定位到第二个账户的收件箱即可。

修改后的完整代码

import win32com.client
import os
from datetime import datetime, timedelta

outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")

# 获取所有Outlook账户并打印,方便确认顺序
accounts = list(mapi.Accounts)
print("所有Outlook账户:")
for idx, account in enumerate(accounts):
    print(f"第{idx+1}个账户:{account.DeliveryStore.DisplayName}")

# 选择第二个账户(Python列表索引从0开始,所以取索引1)
target_account = accounts[1]
# 获取该账户的收件箱(6代表收件箱的常量值)
inbox = target_account.DeliveryStore.GetDefaultFolder(6)

messages = inbox.Items 
received_dt = datetime.now() - timedelta(days=1)
email_subject = 'Base2'
outputDir = 'N:\M_folder'

try:
    for message in list(messages):
        # 可额外添加时间筛选,只处理一天内的邮件
        if email_subject in message.subject and message.ReceivedTime >= received_dt:
            try:
                s = message.sender
                for attachment in message.Attachments:
                    save_path = os.path.join(outputDir, attachment.FileName)
                    attachment.SaveASFile(save_path)
                    print(f"附件 {attachment.FileName} 来自 {s} 已保存")
            except Exception as e:
                print(f"保存附件出错:{str(e)}")
except Exception as e:
    print(f"处理邮件出错:{str(e)}")

关键修改点

  • 将mapi.Accounts转为列表,通过索引[1]直接获取第二个账户
  • 使用target_account.DeliveryStore.GetDefaultFolder(6)替代全局的mapi.GetDefaultFolder(6),这样就能获取到指定账户的收件箱
  • 额外加了message.ReceivedTime >= received_dt的时间筛选,和原代码里的received_dt变量对应,避免处理过旧的邮件(可选保留)

内容的提问来源于stack exchange,提问作者kevin_s_p

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 21:57:03