I currently have the below code that works perfectly if the email is blank but if it comes as part of a chain and it has images (ie company logos in peoples signature etc) then it will only find those. How do i filter it to only select the .csv?
import win32com.client
import os
import time
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item("myemail@gmail.com")
inbox = folder.Folders.Item("Inbox")
msg = inbox.Items
msgs = msg.GetLast()
print (msgs)
print (msgs.Subject)
Filter = "[SenderEmailAddress] = 'senderemail@gmail.com'"
Filter = ("@SQL=" + chr(34) + "urn:schemas:httpmail:subject" +
chr(34) + " Like 'subjectofemail' AND " +
chr(34) + "urn:schemas:httpmail:hasattachment" +
chr(34) + "=1")
Items = inbox.Items.Restrict(Filter)
for Item in Items:
for attachment in Item.Attachments:
print(attachment.FileName)
attachment.SaveAsFile("U:\Downloads\Foldername\Otherfolder\\" + attachment.FileName)
timestr = time.strftime("%Y%m%d")
old_name = r"U:\Downloads\Foldername\Otherfolder\\attachmentfilename.csv"
new_name = r"U:\Downloads\Foldername\Otherfolder\\attachmentfilename " + timestr + ".csv"
os.rename(old_name, new_name)
I have tried a few things ive seen on here but i am very new and have basically created this code from snippets of code i found and got it working with trial and error so im not sure what im doing really. Im trying to learn as i go but assume i need an ELI5 if possible. Thanks
There are two kind of attachments that should be detected:
Attachments with a specific extension - .csv
. You can filter them by checking the Attachment.FileName
property like you have already figured it out.
Embedded images that are used for the message body markup. You can check the message body content for the PR_ATTACH_CONTENT_ID MAPI
property value (the DASL name is "http://schemas.microsoft.com/mapi/proptag/0x3712001F"). Use the Attachment.PropertyAccessor.GetProperty
method for retrieving the value and then check the attachment in the message body using the src
attribute that matches the value of PR_ATTACH_CONTENT_ID
set on the attachment. PR_ATTACH_CONTENT_ID
corresponds to the Content-ID
MIME header when the message is sent.