python-3.xoutlookwin32com

Python obtain latest email from a sender using win32com.client


Trying to obtain the last email sent by a sender in outlook so I can download an attachment.

The issue I have is that the date the email was sent is not consistently sent every day so using something like the below won't work.

CurrentDateTime = dt.datetime.now() - dt.timedelta(days=1)
CurrentDateTime = CurrentDateTime.strftime('%d/%m/%Y %H:%M')
messages = messages.Restrict("[ReceivedTime] > '" + CurrentDateTime +"'")

The below code gives me the correct list but Only want to get the attachment from the latest email.

import win32com.client as client

ol_app = client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = ol_app.GetDefaultFolder(6)
messages = inbox.Items
for message in messages:
    if message.SenderEmailAddress == 'test@test.com':
        print(message.Subject)

I'm planning to use 'for attachment in message.Attachments:'once i have isolated the the last email.


Solution

  • I have a function from a script I made which basically does what you want to do, see if you get an idea from there:

    
    def download_latest_email_attachment(download_folder):
        """Download the latest email attachment that starts with 'Monitoreo Colateral' and ends with '.xlsx'."""
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        inbox = outlook.GetDefaultFolder(6)  # "6" refers to the inbox
        messages = inbox.Items
        messages.Sort("[ReceivedTime]", True)
    
        for message in messages:
            if message.Attachments.Count > 0:
                for attachment in message.Attachments:
                    if attachment.FileName.startswith("Monitoreo Colateral") and attachment.FileName.endswith(".xlsx"):
                        attachment.SaveAsFile(os.path.join(download_folder, attachment.FileName))
                        print(f"Downloaded attachment: {attachment.FileName}")
                        return os.path.join(download_folder, attachment.FileName)
        print("No attachment found.")
        return None