首页 > 解决方案 > 使用 Python 从 Outlook 获取电子邮件列表

问题描述

我正在尝试获取我在 Outlook 中收到的最后 1000 封电子邮件。但是代码只从主文件夹而不是从子文件夹中获取电子邮件。请协助




import win32com.client
import pandas as pd
import dateutil.parser
from datetime import datetime

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
                                    # the inbox. You can change that number to reference
                                    # any other folder
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
i=1
df = pd.DataFrame(columns=['Sender','Subject','DateTime'])
Today = datetime.now().strftime("%m/%d/%Y") # current date and time

while i<1000:
    message=messages[i]
    DT1=message.ReceivedTime
    DT = DT1.strftime("%m/%d/%Y, %H:%M:%S")
    a=message.SenderEmailAddress
    if "-" in a:
        a=a.split("-",1)[1]
    b=message.subject

    df = df.append({'Sender':a,'Subject':b,'DateTime':DT}, ignore_index=True)
    i+=1
df.to_excel("C:/Users/abc/Downloads/Email.xlsx")

标签: pythonoutlookpywin32

解决方案


要对多个文件夹执行搜索,您需要使用类的AdvancedSearch方法ApplicationAdvancedSearch在 Outlook 中使用该方法的主要好处是:

  • 搜索在另一个线程中执行。您不需要手动运行另一个线程,因为该AdvancedSearch方法会在后台自动运行它。
  • 可以在任何位置(即超出某个文件夹的范围)搜索任何项目类型:邮件、约会、日历、便笺等。和Restrict/方法可以应用于特定的集合FindFindNextItems
  • 完全支持 DASL 查询(自定义属性也可用于搜索)。您可以在 MSDN中的过滤文章中阅读有关此内容的更多信息。为了提高搜索性能,如果为商店启用了即时搜索,则可以使用即时搜索关键字(请参阅类的IsInstantSearchEnabled属性Store)。
  • 您可以使用 Search 类的 Stop 方法随时停止搜索过程。

阅读有关该AdvancedSearch方法的更多信息并在 Outlook 中的高级搜索中以编程方式查找示例:C#、VB.NET文章。

类的Restrictor Find/FindNext方法Items仅允许根据您的条件从单个文件夹中获取项目。


推荐阅读