У меня есть код, который просматривает входящие сообщения Outlook для определенных отправителей, а затем сохраняет вложения из этих сообщений в папку на моем рабочем столе. Он также добавляет адрес отправителя к имени счета, чтобы быстро определить, какие счета принадлежат какой компании.
Проблема в том, что в некоторых электронных письмах используется имя отправителя, которое не имеет отношения к компании, или они приходят с ненадежного адреса, например, 'abc@123.com, отправленного от имени def@456.com'и эти адреса отказов похожи на бред. Я не нашел атрибут SentOnBehalfOfAddress или чего-либо подобного для почтовых элементов, поэтому сейчас я просто использую SenderEmailAddress. Есть ли какие-либо предложения о том, как получить желаемый результат?
import win32com.client, os, datetime, sys
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
try:
itinbox = outlook.Folders("IT Department").Folders('Inbox')
itcontents = itinbox.Items
except UnicodeEncodeError: #unsupported characters
print("A message had unsupported characters.")
todayDate = datetime.date.today()
senderDict = {"dictionary of email address and sender names" : "goes here"}
#####Loop to check messages
check = 0
for msg in reversed(itcontents): #most recent to oldest
if msg.Class == 43: #avoid attribute error for non mail-item objects
try:
if str(msg.SenderEmailAddress) in senderDict or str(msg.SentOnBehalfOfName) in senderDict:
check += 1
print(check, "messages from", msg.SenderEmailAddress)
for x in msg.Attachments:
if str(".pdf").casefold() in str(x): #pdf's only
#x refers to the attachment
x.SaveAsFile(r"C:\Users\...\Desktop\Invoices from Outlook\\" + str(msg.SenderEmailAddress) + x.FileName)
print("Saved attachment", x)
except UnicodeEncodeError: #unsupported characters
print("Subject line could not be parsed.")
except AttributeError: #The email was the wrong class for the attribute
print("Attribute error")
input("Press any key to exit.")
Вывод выглядит так в оболочке, но сохраненный файл имеет адрес электронной почты + имя файла счета-фактуры, например, 'messaging-service@post.xero.comInvoice INV-001150.pdf '.
1 messages from messaging-service@post.xero.com
Saved attachment Invoice INV-001150.pdf
2 messages from messaging-service@post.xero.com
Saved attachment Invoice INV-001149.pdf
[...]
22 messages from bounce+enterprise+ld5ormsh69xl@return.recurly.com
Saved attachment invoice_10015059.pdf
В конечном итоге я хотел бы получить вывод файла с легко идентифицируемым отправителем и номером счета, например ' Amazon Web Services Invoice1234.pdf '