Greencolor
Greencolor

Reputation: 695

save outlook attachments with python

Every Monday I receive the attachments with the slightly changed subject title. Constant part of the subject title is PB Report and will have the Monday's date. For example I received email this Monday with subject PB Report - 13.12.2021, last week PB Report - 06.12.2021 and so on. I would like to implement the GetLast in this code in order to get only the newest sent report. Also, how do I tell python to search the subject which starts with PB Report and dont look at the rest of the title. I tried wildcard(*) as save_attachments('PB Report*') but did not work.

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')

I also have the alternative code but when i run this code i never get the result nor error. It takes.

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)))

Upvotes: 2

Views: 9084

Answers (1)

hc_dev
hc_dev

Reputation: 9418

The wildcard for parameter subject wont work because parameter subject is used as string when comparing for equality in message.Subject == subject.

You could instead use string-method startswith on the message subject like message.Subject.startswith(subject_prefix) and call your method with a common prefix like save_attachments('PB Report - ').

Furthermore use the attachment.FileName to construct the output-file path.

You could use GetLast() or Sort() with appropriate message property to filter on the newest sent report. Or you could parse the dates in message's subject and sort them accordingly. However this would deserve another question, own research and further specification and focus.

Solution

An example solution could be as follows (see comments for adjustments):

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

Alternatively use GetLast() if you know the messages only contain desired ones, sorted by date.

message = messages.GetLast()
while message:  # to test if there is a (last) message at all
    # save attachment

Related questions

Upvotes: 5

Related Questions