使用win32在Python中从Outlook Exchange提取发件人的电子邮件地址

11

我正在试图使用Python中的win32包从Outlook 2013中提取发件人的电子邮件地址。我的收件箱中有两种类型的电子邮件地址,一种是Exchange,另一种是SMTP。如果我尝试打印Exchange类型的发件人电子邮件地址,我会得到这个结果:

/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP(FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=6F467C825619482293F429C0BDE6F1DB-

我已经浏览了这个链接,但是无法找到一个可以提取smtp地址的函数。

以下是我的代码:

from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
folders = inbox.Folders
for msg in all_inbox:
   print msg.SenderEmailAddress  

目前,所有的电子邮件地址都是这样的:

/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP(FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=6F467C825619482293F429C0BDE6F1DB-

我在VB.net中找到了这个解决方案链接,但不知道如何用Python重写相同的东西。

3个回答

20
首先,如果您在文件夹中有除MailItem以外的项,例如ReportItemMeetingItem等,则您的代码将无法运行。您需要检查所有Outlook对象公开的Class属性是否为43 (olMail)。
其次,您需要检查发件人电子邮件地址类型,并仅针对"SMTP"地址类型使用SenderEmailAddress属性。在VB中:
 for each msg in all_inbox
   if msg.Class = 43 Then
     if msg.SenderEmailType = "EX" Then
       print msg.Sender.GetExchangeUser().PrimarySmtpAddress
     Else
       print msg.SenderEmailAddress 
     End If  
   End If
 next

1
谢谢兄弟 :) 你节省了我很多时间。 - python
@python,有没有办法从电子邮件正文中单独提取电子邮件签名?? - Pravin
1
@Pravin - 不,签名只是HTML正文的一部分,特别是在传入邮件中。这并没有什么特别之处。 - Dmitry Streblechenko

12

我正在修改上面给出的Python程序。

from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
folders = inbox.Folders

for msg in all_inbox:
       if msg.Class==43:
           if msg.SenderEmailType=='EX':
               print msg.Sender.GetExchangeUser().PrimarySmtpAddress
           else:
               print msg.SenderEmailAddress

这将仅在您的收件箱文件夹中打印出所有发件人的电子邮件地址。

1
在我的情况下,这个操作失败了,出现了“AttributeError: 'NoneType' object has no attribute 'PrimarySmtpAddress'”错误。怎么可能没有PrimarySmtpAddres呢? - FaCoffee
很可能,在测试时您的文件夹中没有包含任何电子邮件。 - dravid07

2

今天我在使用win32com时遇到了同样的问题。我在这里找到了解决方案。

根据你的示例,代码应该是:

from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
folders = inbox.Folders

for msg in all_inbox:
   if msg.Class==43:
       if msg.SenderEmailType=='EX':
           if msg.Sender.GetExchangeUser() != None:
               print msg.Sender.GetExchangeUser().PrimarySmtpAddress
           else:
               print msg.Sender.GetExchangeDistributionList().PrimarySmtpAddress
       else:
           print msg.SenderEmailAddress

这应该解决群发邮件的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接