python - 使用 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")
解决方案
要对多个文件夹执行搜索,您需要使用类的AdvancedSearch
方法Application
。AdvancedSearch
在 Outlook 中使用该方法的主要好处是:
- 搜索在另一个线程中执行。您不需要手动运行另一个线程,因为该
AdvancedSearch
方法会在后台自动运行它。 - 可以在任何位置(即超出某个文件夹的范围)搜索任何项目类型:邮件、约会、日历、便笺等。和
Restrict
/方法可以应用于特定的集合Find
。FindNext
Items
- 完全支持 DASL 查询(自定义属性也可用于搜索)。您可以在 MSDN中的过滤文章中阅读有关此内容的更多信息。为了提高搜索性能,如果为商店启用了即时搜索,则可以使用即时搜索关键字(请参阅类的
IsInstantSearchEnabled
属性Store
)。 - 您可以使用 Search 类的 Stop 方法随时停止搜索过程。
阅读有关该AdvancedSearch
方法的更多信息并在 Outlook 中的高级搜索中以编程方式查找示例:C#、VB.NET文章。
类的Restrict
or Find
/FindNext
方法Items
仅允许根据您的条件从单个文件夹中获取项目。
推荐阅读
- java - Spring使用JSONObject字段反序列化对象
- javascript - 画布 - 将画布保存为图像后,橡皮擦在画布上绘制黑线
- node.js - 如何使用 passport.js 使用已登录用户的 accessToken 获取 JSON?
- azure - access_denied AADSTS50105:已登录用户未分配给应用程序的角色
- sqlite - 浏览器存储导入json文件
- html - 它没有显示我在 base.css 文件中设计的菜单栏
- deployment - Sharepoint 在线代码存储库和持续部署
- python - 如何检查对象的类型为“dict_items”?
- android - 当应用程序在后台时,带有数据的 FCM Intent 在哪里?
- ruby - Ruby 应用程序的 Dockerfile 中的文件权限问题