无法在Outlook电子邮件Python中提取收件人名称

时间:2017-04-12 21:38:55

标签: python-3.x win32com

我正在尝试提取收件人地址,当我打印时,我得到以下内容:

<COMObject <unknown>>

我有以下代码。我也试过Receipient.Name

import win32com.client
import sys
import csv


outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()
subject_list = []
sender_list = []
recipients_list = []
i = 0

while message:

    subject = message.Subject
    sender = message.SenderName
    recipients = message.Recipients


    subject_list.append(str(subject))
    sender_list.append(str(sender))
    recipients_list.append(recipients)
    i+=1

    message = messages.GetPrevious()
    if i > 10:
        break

for subject in subject_list:
    print(subject)   
for sender in sender_list:
    print(sender)
for recipient in recipients_list:
    print(recipient)    

如何获取收件人姓名或电子邮件地址?

1 个答案:

答案 0 :(得分:1)

我认为“message.Recipients”会为您提供Recipient Collection,而不是特定的收件人。您可以通过将集合中的各个收件人添加到列表中来解决此问题。

要获取电子邮件地址,如果地址为您提供Exchange用户地址,则可能需要一些额外的导航,因此您可以使用Address Entry中的函数来检索它。 (您可以通过在这些链接中导航msdn文档来了解有关这些Outlook对象的更多信息。)

我在您的代码中添加了几行,以下内容对我有用。

while message:

    subject = message.Subject
    sender = message.SenderName
    recipients = message.Recipients

    subject_list.append(str(subject))
    sender_list.append(str(sender))
    #This loop will add each recipient from an email's Recipients Collection to your list individually
    for r in recipients:
        recipients_list.append(r)
    i+=1

    message = messages.GetPrevious()
    if i > 10:
        break

for subject in subject_list:
    print(subject)
for sender in sender_list:
    print(sender)
for recipient in recipients_list:
    #Now that the for loop has gone into the Recipient Collection, this should print the recipient name
    print(recipient)
    #This is the "Address", but for me they all appeared as Exchange Users, rather than explicit email addresses.
    print(recipient.Address)
    #I used this code to get the actual addresses
    print(recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddress)