【问题标题】:How to access emails sender in Outlook using Pywin32如何使用 Pywin32 在 Outlook 中访问电子邮件发件人
【发布时间】:2021-06-14 13:32:02
【问题描述】:

例如,我想打印一些关于具有 Category="Backlog" 的电子邮件的信息。我使用pywin32 库如下代码:

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

def print_messages(messages, sCategory, f):
    msgs = messages.Restrict("[Categories] = '" + sCategory + "'")
    for message in list(msgs):
        try:
            if message.Class == 43:
                if message.SenderEmailType == "EX":
                    strSender = message.Sender.GetExchangeUser().PrimarySmtpAddress
                else:
                    strSender = message.SenderEmailAddress
            f.write(message.EntryID + "\t" + strSender + message.ConversationTopic + "\t" + message.ReceivedTime.strftime("%Y-%m-%d %H:%M") + "\t" + message.Categories + "\n")
        except Exception as e:
            print("Oops!", sys.exc_info()[0], "occurred.")

def main():
    outlook = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")
    inbox = outlook.GetDefaultFolder(6)
    messages = inbox.Items
    now = datetime.now()
    f = open("C:/Temp/outlook_emails_" + now.strftime("%Y-%m-%d_%H-%M-%S") + ".txt", "a")
    print_messages(messages, "Backlog", f)
    f.close()

if __name__ == "__main__":
    main()

当此代码运行时,它无法获取电子邮件发件人。发生异常并打印如下行:

Oops! <class 'pywintypes.com_error'> occurred.
Oops! <class 'pywintypes.com_error'> occurred.
Oops! <class 'pywintypes.com_error'> occurred.
Oops! <class 'pywintypes.com_error'> occurred.

问题: strSender = message.Sender.GetExchangeUser().PrimarySmtpAddress 并在线 strSender = message.SenderEmailAddress。 不知道如何正确访问发件人的电子邮件地址!!

使用的版本:

  • Windows 10(64 位)
  • Outlook v16(64 位)
  • Python 3.9.5(64 位)
  • pywin32版本:300

【问题讨论】:

    标签: python python-3.x outlook pywin32


    【解决方案1】:

    你永远不会检查 GetExchangeUser 返回一个有效的对象而不是 null。当前配置文件必须包含容纳 GAL 用户的原始 Exchange 服务器。

    在使用GetExchangeUser之前,检查PidTagSenderSmtpAddress MAPI 属性是否可用message.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x5D01001F")

    【讨论】:

    • 在 try/catch 块中添加行:print(message.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x5D01001F")),它会导致相同的异常:Oops! &lt;class 'pywintypes.com_error'&gt; occurred.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    相关资源
    最近更新 更多