现在我写了一个代码,每天运行它来获取昨天电子邮件的附件。当我运行它时,附件没有下载,而是得到了一个名为"@"的文件。
下面是代码:
import win32com.client
import os
from datetime import datetime, date, time, timedelta
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("Inbox Subfolder Name")
messages = inbox.Items
message = messages.GetFirst()
subject = message.Subject
# Get yesterdays date for the purpose of getting emails from this date
d = (date.today() - timedelta (days=1)).strftime("%y-%m-%d")
yesterdaydate=("20"+d)
print yesterdaydate
get_path_clt1 = "Folder Location" + yesterdaydate+"\"
if os.path.exists(get_path_clt1):
print " File Exists"
else:
os.mkdir(get_path_clt1)
for m in messages:
date = str(m.senton)
date_time_obj = datetime.strptime(date,'%m/%d/%y %H:%M:%S')
messagedate=date_time_obj.date()
if str(yesterdaydate) == str(messagedate) and (m.Subject == "Subject Name to compare") :
print (message)
print (messagedate)
attachments = message.Attachments
num_attach = len([x for x in attachments])
print("test-1")
for x in range(1, num_attach+1):
print("test-in-1")
attachment = attachments.Item(x)
attachment.SaveAsFile(os.path.join(get_path_clt1,attachment.FileName))
print (attachment)
print ("---------------------")
break
message = messages.GetNext()
else:
message = messages.GetNext()
首先,不需要迭代所有附件来获得编号:
num_attach = len([x for x in attachments])
相反,您可以使用"附件"。Count属性,返回一个整数,指示指定集合中对象的计数。
其次,确保指定了一个有效的文件名:
attachment.SaveAsFile(os.path.join(get_path_clt1,attachment.FileName))
我建议在生成自己的attachment.FileName
值之前先检查一下。
最后,您可以查看附件。Type属性,返回指示指定对象类型的OlAttachmentType
常量。