使用Python在GAL中更快地搜索电子邮件

2024-05-16 05:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个Python脚本,根据1500个Outlook联系人(20000个联系人中的一个)的电子邮件获取不同的信息。直到现在,我还是做到了:

def grab_user_details(email):
    first_name, last_name, department, location = '', '', '', ''
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    gal = outlook.Session.GetGlobalAddressList()
    entries = gal.AddressEntries
    for i in entries:
        user = i.GetExchangeUser()
        if user is not None:
            if user.PrimarySmtpAddress == email:
                first_name = email.split("@")[0].split(".")[0].title()
                last_name = email.split("@")[0].split(".")[1].title()
                department = user.Department
                location = user.OfficeLocation
                print(email, first_name, last_name, department, location)
                break

最后,代码只是针对特定电子邮件在GAL中进行迭代。找到后,它会中断,并继续搜索下一封电子邮件。此方法对于以A或至少B开头的电子邮件是快速的。。。但是当你有一个女孩有20000封电子邮件时,你不能只等2天就让她完成整个字母表

有没有更快的方法

谢谢


Tags: nameif电子邮件email联系人locationfirstentries
2条回答

使用Namespace类的CreateRecipient方法根据电子邮件地址获取收件人类的实例

Sub TestRecipient()
 Dim myNamespace As Outlook.NameSpace 
 Dim myRecipient As Outlook.Recipient 
 
 Set myNamespace = Application.GetNamespace("MAPI") 
 Set myRecipient = myNamespace.CreateRecipient("address@domain.com") 
 
 myRecipient.Resolve 
 
 If myRecipient.Resolved Then 
 
   ' do some stuff here
 
 End If 
 
End Sub 

Recipient.AddressEntry属性返回与解析的收件人对应的AddressEntry对象。访问AddressEntry属性将强制解析未解析的收件人名称。如果无法解析名称,则返回错误。如果收件人已解析,Resolved属性为True

然后,您可以使用AddressEntry.GetExchangeUser方法,如果AddressEntry属于诸如全局地址列表(GAL)之类的交换AddressList对象并与交换用户相对应,则该方法将返回表示AddressEntry的ExchangeUser对象

根据@Eugene Astafiev的回答(谢谢!),我想出了以下代码:

def grab_user_details(email):
    name, department, location = '', '', ''
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    user = outlook.Session.CreateRecipient(email)
    user.Resolve()
    print(user.Resolved)
    try:
        name = user.AddressEntry.GetExchangeUser().Name
        department = user.AddressEntry.GetExchangeUser().Department
        location = user.AddressEntry.GetExchangeUser().OfficeLocation
        print(email, name, department, location)
    except:
        print("user NA")

这种方法比在GAL中搜索要快得多

还有一件事我需要解决:不幸的是,有些用户有2个电子邮件地址',并且.CreateRecipient(电子邮件)不返回任何内容,尽管outlook可以找到它。我需要再深入一点

相关问题 更多 >