[英]Download Attachments From Outlook using Pythin Script
現在我編寫了一個代碼,每天運行它來獲取昨天電子郵件的附件。 當我運行它時,附件沒有下載,而是我得到一個名為“@”的文件。
下面是代碼:
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])
相反,您可以使用Attachments.Count屬性,該屬性返回一個 integer,指示指定集合中的對象計數。
其次,確保您指定了一個有效的文件名:
attachment.SaveAsFile(os.path.join(get_path_clt1,attachment.FileName))
我建議在之前檢查attachment.FileName
值或生成自己的值。
最后,您可以檢查Attachment.Type屬性,該屬性返回一個指示指定 object 類型的OlAttachmentType
常量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.