【问题标题】:Connect to an outlook email other than my local outlook using python使用 python 连接到本地 Outlook 以外的 Outlook 电子邮件
【发布时间】:2018-12-26 16:56:48
【问题描述】:

我正在编写一个python 脚本,该脚本连接到 Outlook 并保存电子邮件中的附件(如果指定路径中有)。

目前,该脚本连接到我的本地 outlook

如何连接到本地以外的 Outlook 电子邮件?

下面是我目前使用的脚本

import os 
os.environ["NLS_LANG"] = ".AL32UTF8"
import socket
import win32com.client
import datetime
from datetime import timedelta

hstname = socket.gethostname()

date_time = datetime.datetime.now().strftime("%m%d%Y%H%M%S")
#connects to the local outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders("Received Files")
move_fol = inbox.Folders("Processed_Files")
messages = inbox.Items
attachment_name = 'bjc_file'

#Loop to pick messages that are unread
for message in messages:
    if message.Unread == True:
        attachments = message.Attachments
        for attachment in attachments:
            if attachment_name in attachment.Filename:
                for i in range (attachments.count):
                    attachment = attachments.Item(i+1)
                    attachmentname = str(attachment).replace('.csv', '_' + date_time + '.csv')
                    attachment.SaveASFile('C:\\Users\\Desktop\\Work\\BJC_Files' + '\\' + attachmentname)
                    message.move(move_fol)

【问题讨论】:

    标签: python-3.x outlook python-3.5 win32com


    【解决方案1】:

    Outlook 对象模型仅允许您使用在 Outlook 中配置的现有配置文件。如果配置了本地配置文件,您可以在创建 Outlook.Application 的实例、从 Application.GetNamespace("MAPI") 检索 Namespace 对象并使用配置文件名称调用 Namespace.Logon 后指定该配置文件。

    请记住,由于 Outlook 是单例的,如果它已经使用不同的配置文件运行,则调用 Namespace.Logon 将无效。

    如果要连接到任意 Exchange 邮箱,可以使用 EWSREST API。您还可以使用Redemption 及其RDOSession.LogonHostedExchangeMailbox 方法 - 它将创建(和删除)一个配置为访问指定邮箱的临时本地配置文件。

    无论您选择使用哪种 API,都不要使用删除(通过调用 Move)其中一些元素的 foreach 循环。使用从 Items.Count 到 1 的向下 for 循环。

    【讨论】:

    • 谢谢德米特里!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2014-10-16
    • 2019-01-09
    • 2016-02-19
    相关资源
    最近更新 更多