[英]Python: Downloading Outlook Attachments and Change Filename on Save
[英]save outlook attachments with python
每個星期一我都會收到主題標題略有改變的附件。 主題標題的固定部分是PB 報告,日期為星期一。 例如,我本周一收到了 email 的主題PB Report - 13.12.2021 ,上周的PB Report - 06.12.2021等等。 我想在此代碼中實現GetLast
以便僅獲取最新發送的報告。 另外,我如何告訴 python 搜索以 PB Report 開頭的主題,不要看標題的 rest。 我嘗試將通配符(*)作為save_attachments('PB Report*')
,但沒有奏效。
import datetime
import os
import win32com.client
path = r"C:/Users/greencolor/Desktop/Autoreport/"
today = datetime.date.today()
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
def save_attachments(subject):
for message in messages:
if message.Subject == subject:
for attachment in message.Attachments:
print(attachment.FileName)
attachment.SaveAsFile(os.path.join(path, str(attachment)))
if __name__ == "__main__":
save_attachments('PB Report - 13.12.2021')
我也有替代代碼,但是當我運行此代碼時,我永遠不會得到結果或錯誤。 它需要。
import os
import win32com.client
path = r"C:/Users/greencolor/Desktop/Autoreport/"
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()
while message:
if 'PB' in message.subject and 'Report' in message.subject:
for attachment in message.Attachments:
print(attachment.FileName)
attachment.SaveAsFile(os.path.join(path, str(attachment)))
參數subject
的通配符不起作用,因為在比較message.Subject == subject
中的相等性時,參數subject
被用作字符串。
您可以改為在消息主題上使用 string-method startswith
,例如message.Subject.startswith(subject_prefix)
並使用通用前綴(例如save_attachments('PB Report - ')
)調用您的方法。
此外,使用attachment.FileName
構造輸出文件路徑。
您可以使用帶有適當消息屬性的GetLast()
或Sort()
來過濾最新發送的報告。 或者您可以解析消息主題中的日期並相應地對它們進行排序。 然而,這將值得另一個問題,自己的研究和進一步的規范和關注。
一個示例解決方案可能如下(請參閱調整評論):
def save_attachments(subject_prefix): # changed parameter name
messages.Sort("[ReceivedTime]", True) # sort by received date: newest to oldest
for message in messages:
if message.Subject.startswith(subject_prefix): # changed test
print("saving attachments for:", message.Subject)
for attachment in message.Attachments:
print(attachment.FileName)
attachment.SaveAsFile(os.path.join(path, str(attachment.FileName))) # changed to file-name
return # exit after first matched message
如果您知道消息僅包含所需的消息,或者按日期排序,則可以使用GetLast()
。
message = messages.GetLast()
while message: # to test if there is a (last) message at all
# save attachment
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.