【发布时间】:2021-07-20 21:19:07
【问题描述】:
希望你一切都好。
我一直在用网络抓取进行一些 python 练习,并且遇到了 win32com 库,并且一直在努力从我的 Outlook 电子邮件中获取附件(它只是一个)!我设法通过以下代码查看了所有电子邮件。我想知道您是否可以帮助我获取名为“data_bay1.xlsx”的附件文件,因为我对错误感到困惑。到目前为止,我可以从电子邮件中获取数据,但是当我尝试运行它时,我无法获取附件 xlsx 文件和代码的附件部分,它给了我错误。请看看我到目前为止做了什么,我希望你们中的任何人都可以提供帮助。我正在使用 anaconda 和 windows。先感谢您!亲切的问候,莉莉
import win32com.client
#connecting python to outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
#connecting to our inbox
inbox = outlook.GetDefaultFolder(6)
(inbox)
# here we are ensuring the indexes exist so we can grab data
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
messages = inbox.items
messages = messages.GetFirst() earlier
# get the last email
#message = messages.GetLast()
(message)
#to loop through the email in the inbox
while True:
try:
print(message.subject) # get the subject of the email
# if you use messages.GetFirst() earlier
message = messages.GetNext()
# if you use messages.GetPrevious() earlier
#message = messages.GetPrevious()
except:
# if you use messages.GetFirst() earlier
message = messages.GetNext()
# if you use messages.GetPrevious() earlier
#message = messages.GetPrevious()
# get the attachment
attachments = message.Attachments# return the first item in attachments
attachment = attachments.Item(1)
# the name of attachment file
attachment_name = str(attachment).lower()
attachment.SaveASFile(path+ 'C:\Users\lily\OneDrive - Dataenv\Documents + attachment_data_bay1)
【问题讨论】:
标签: python outlook xlsx win32com