![](/img/trans.png)
[英]How to save outlook email attachments with Python, on Virtal Desktop (VMWare)
[英]How to save all attachments in email using for loop in Python and Outlook?
如果我的电子邮件中有1个附件,这就是我的代码,可以很好地运行。 问题出现在电子邮件中有多个附件时,我希望对所有附件执行功能。
def get_email():
import win32com.client
import os
import time
import datetime as dt
date_time = time.strftime('%m-%d-%Y')
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst() # any time calling GetFirst(), you can get GetNext()....
# body_content = message.body
try:
attachments = message.Attachments
attachment = attachments.Item(1)
report_name = date_time + '_' + attachment.FileName
attachment.SaveASFile(os.getcwd() + '\\' + report_name)
print('Attachment saved: ' + report_name)
except: #***********add error logging here**************
print('No attachment found.')
我如何将其放入for循环并说-对于每个x, attachment = attachments.Item(x)
-保存该附件,并基于刚刚保存的附件运行另一个函数。 有没有一种方法可以定义x变量,以便给我电子邮件中的附件数量,然后通过for循环运行它? 还是有一种方法可以运行for循环,并且-在不产生任何错误的情况下-找到最后一个附件后停止运行?
看起来Attachments集合可以像普通列表一样在for循环中工作。 我得到以下内容来将每个附件保存在电子邮件中,并且不会在没有附件的电子邮件中引发错误:
import win32com.client
import os
import time
import datetime as dt
date_time = time.strftime('%m-%d-%Y')
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst()
attachments = message.Attachments
# The following line works, so you can see how many attachments are on an item
print len(attachments)
# Here's another way to get the number of attachments
print attachments.Count
# since attachments works similar to a list, a for loop works
# if there are no attachments, it won't enter the for loop, and won't throw an error
for attachment in attachments:
report_name = date_time + '_' + attachment.FileName
attachment.SaveASFile(os.getcwd() + '\\' + report_name)
print('Attachment saved: ' + report_name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.