[英]Unable to download attachments from outlook using Python || Python 3.10
我正在嘗試從 outlook 下載帶有特定主題行的附件。 它顯示已完成,但沒有下載附件。 下面附上我的代碼,如果我遺漏了什么,請幫忙。
# import libraries
import win32com.client
import re
import datetime
import pathlib2 as pathlib
# set up connection to outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst()
today_date = str(datetime.date.today())
while True:
try:
current_sender = str(message.Sender).lower()
current_subject = str(message.Subject).lower()
# find the email from a specific sender with a specific subject
# condition
if re.search('AllSalons was executed at',current_subject) != None:
#if re.search('AllSalons was executed at',current_subject) != None and re.search(sender_name,current_sender) != None:
print(current_subject) # verify the subject
print(current_sender) # verify the sender
attachments = message.Attachments
attachment = attachments.Item(1)
attachment_name = str(attachment).lower()
attachment.SaveASFile(pathlib.path + 'C:\\Users\\UserTest\\Desktop\\Folder\\Subject Line\\Nov' + attachment_name)
else:
pass
message = messages.GetNext()
except:
message = messages.GetNext()
break
print("Finished")
首先,您需要確保將有效的文件路徑傳遞給Attachment
class 的SaveAsFile
方法:
attachment.SaveASFile(pathlib.path + 'C:\\Users\\UserTest\\Desktop\\Folder\\Subject Line\\Nov' + attachment_name)
確保該文件夾存在於磁盤上並且文件名中不包含禁止的符號。 Windows 和 Linux 不允許在文件名中使用某些符號,請參閱What characters are forbidden in Windows and Linux directory names? 想要查詢更多的信息。
其次,無需遍歷 Outlook 文件夾中的所有項目並檢查Subject
屬性值,您需要使用Items
class 的Find
/ FindNext
或Restrict
方法。因此,在這種情況下,您只能處理與您的搜索相對應的項目標准並迭代它們。 在我為技術博客撰寫的文章中閱讀有關這些方法的更多信息:
您正在連接兩條路徑,其中一條是完全限定路徑( "c:\"
..)。 它唯一可行的方法是pathlib.path
為空。
另外,更換線
attachment_name = str(attachment).lower()
和
attachment_name = str(attachment.FileName).lower()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.