用Python win32com读取Outlook邮件的功能详尽文档
我正在尝试更好地理解如何通过win32com与Outlook进行交互。不过,我发现很难找到清晰的文档,能让我有效地使用win32com来读取邮件。从我目前的调查来看,很多用户似乎都有类似的困惑。因此,我有以下信息和请求:
有没有人能:
1. 给我一个清晰文档的链接(如果有的话)
2. 对下面的内容进行详细说明
以下是我根据阅读其他人的代码所找到的当前功能。
看看下面的代码:
import win32com
outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.GetDefaultFolder(6)
messages=inbox.Items
for message in messages:
attachments = message.attachments
for attachment in attachments:
pass
上面使用的对象有我所知道的以下功能:
收件箱 -
.Folders
.Items
邮件 -
.GetFirst()
.GetLast()
.GetNext()
.GetPrevious()
.Attachments
单条邮件 -
.Subject
.Body
.To
.Recipients
.Sender
.Sender.Address
附件 -
.item()
.Count
单个附件 -
.filename
如果你知道更多的功能,请在你的回答中补充。
6 个回答
这个页面绝对是关于pywin32最全面的资源了!
我再补充一点:
message.senton.date() # for received date only
message.senton.time() # for received time only
message.senton # for date and time
另外,我刚发现消息属性,比如senton、attachment,以及上面Genome分享的“Interop Outlook Mailitem Properties”中显示的所有其他属性,可以用全小写、全大写或者混合的方式来写。
关于附件的内容,可以参考这个链接:https://learn.microsoft.com/en-us/office/vba/api/outlook.attachment(查看属性)。
attachment.FileName
attachment.Type
attachment.Position
attachment.BlockLevel
attachment.Class
attachment.DisplayName
attachment.Parent
attachment.Session
attachment.Size
attachment.Index
attachment.Application
我想补充一下关于如何在文件夹中导航的内容——这些信息都是来自微软的文档,但在这里提到可能会更有帮助,特别是如果你想在Outlook的文件夹结构中去除收件箱以外的地方。
你可以通过 folders
来浏览文件夹集合——注意在这种情况下,GetNamespace
后面没有 GetDefaultFolder
(否则你很可能会直接进入收件箱)。
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace('MAPI')
folder = outlook.Folders[1]
数字是你想访问的文件夹的索引。要找出里面有多少个子文件夹,可以使用:
folder.Count
如果还有更多的子文件夹,你可以再用一个 Folders
来深入查看:
folder.Folders[2]
Folders
会返回一个子文件夹的列表,所以要获取当前目录下所有文件夹的名称,你可以用一个简单的循环。
for i in range(folder.Count):
print (folder[i].Name)
每个子文件夹都有一个 .Items
方法,可以用来获取邮件列表。
对于大家想知道如何访问默认文件夹,不仅仅是“收件箱”,这里有一个列表:
3 Deleted Items
4 Outbox
5 Sent Items
6 Inbox
9 Calendar
10 Contacts
11 Journal
12 Notes
13 Tasks
14 Drafts
还有更多的文件夹(比如提醒、同步错误等等);你可以用这段代码获取完整的列表(灵感来自于 John Cook的解决方案):
import win32com
outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
for i in range(50):
try:
box = outlook.GetDefaultFolder(i)
name = box.Name
print(i, name)
except:
pass
我没有把完整的列表贴在这里,因为我的列表是波兰语的,可能对大家没什么帮助。
这里的“Visual Basic for Applications”参考资料会对你很有帮助。可以先从这个链接开始...
比如,我可以看到,消息可能会有比你上面列出的更多的属性。例如:
- message.CC
- message.Importance
- message.LastModificationTime