【问题标题】:Extract Recipients Email Address in Outlook using Python Win32com使用 Python Win32com 在 Outlook 中提取收件人电子邮件地址
【发布时间】:2022-01-13 11:58:24
【问题描述】:

我正在尝试使用 Win32com 客户端在 Python 中提取收件人电子邮件地址。

到目前为止,这是我的代码:

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders["[my email address"].Folders["Inbox"]


def get_email_address():
    for message in inbox.Items:
        print("========")
        print("Subj: " + message.Subject)
        print('To:', message.Recipients)    #this part does not work
        print("Email Type: ", message.SenderEmailType)
        if message.Class == 43:
            try:
                if message.SenderEmailType == "SMTP":
                    print("Name: ", message.SenderName)
                    print("Email Address: ", message.SenderEmailAddress)
                    print('To:', message.Recipients)    #this part does not work
                    print("Date: ", message.ReceivedTime)
                elif message.SenderEmailType == "EX":
                    print("Name: ", message.SenderName)
                    print("Email Address: ", message.Sender.GetExchangeUser(
                                                              ).PrimarySmtpAddress)
                    print('To:', message.Recipients)    #this part does not work
                    print("Date: ", message.ReceivedTime)
            except Exception as e:
                print(e)
                continue


if __name__ == '__main__':
    get_email_address()

如您所见,我可以获取发件人电子邮件地址...但是如何获取收件人电子邮件地址?

【问题讨论】:

  • RecipientsRecipient 对象的集合,而不是电子邮件地址列表。 docs.microsoft.com/en-us/office/vba/api/outlook.recipients 您需要遍历它,例如 for recip in message.Recipients: print(recip.Address)
  • 谢谢,但按照您的建议应用以下代码只会给我收件人姓名,而不是收件人电子邮件地址。对于收件箱中的消息。项目:对于消息中的 x。收件人:打印(x.AddressEntry)

标签: python email outlook win32com


【解决方案1】:

这与您对发件人所做的类似 - 循环遍历 MailItem.Recipients 集合中的收件人,并为每个 Recipient 使用 Recipient.AddressEntry 属性来执行您已经使用 MailItem.Senderproperty 执行的操作。

另请注意,这不是最有效的方法 - 如果配置文件没有父 Exchange 服务器,例如打开地址条目可能会很昂贵或完全不可能。如果您正在处理独立的 MSG 文件或从 Exchange 邮箱复制到 PST 的邮件。在大多数情况下,SMTP 地址可直接在邮件中使用,例如来自PidTagSenderSmtpAddress(DASL 名称http://schemas.microsoft.com/mapi/proptag/0x5D01001F),可以使用MailItem.PropertyAccessor.GetProperty 访问。同样,收件人 SMTP 地址可能在 PR_SMTP_ADDRESS 属性中可用(DASL 名称 http://schemas.microsoft.com/mapi/proptag/0x39FE001F,使用 Recipient.PropertyAccessor.GetProperty) - 您可以在 OutlookSpy 中查看这些属性(单击 IMessage 按钮属性)。

【讨论】:

  • 这似乎不起作用 - 对于收件箱中的消息。项目:对于消息中的 x。收件人:打印(x.AddressEntry)。我不太在乎效率——我只需要一个简单的代码就可以快速解决这个烦人的问题。
  • print(x.AddressEntry) 毫无意义——它是一个对象,而不是一个属性。你需要print(x.AddressEntry.GetExchangeUser().PrimarySmtpAddress)
  • 感谢您的帮助!
猜你喜欢
  • 2019-01-09
  • 1970-01-01
  • 2016-02-19
  • 2023-01-26
  • 2017-01-08
  • 1970-01-01
  • 2012-09-20
  • 2011-12-17
  • 2015-10-15
相关资源
最近更新 更多