使用win32

时间:2015-07-24 20:13:12

标签: python email outlook pywin32 win32com

我正在尝试使用python中的win32包从outlook 2013中提取发件人的电子邮件地址。我的收件箱,交换和smtp有两种电子邮件地址类型。如果我尝试打印发件人的Exchange类型的电子邮件地址,我会得到这个:

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

我已经完成了这个link但找不到一个可以提取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 link中找到了解决方法,但不知道如何在Python中重写相同的东西。

3 个答案:

答案 0 :(得分:7)

首先,如果文件夹中有MailItem以外的项目,例如ReportItem,MeetingItem等,您的代码将失败。您需要检查类属性。

其次,您需要检查发件人电子邮件地址类型,并仅将SenderEmailAddress用于“SMTP”地址类型。在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 :(得分:4)

我只是在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

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

答案 2 :(得分:0)

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

以您的示例为例:

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

这应该可以解决群邮件问题。