pythonvariablesoutlookattachmentsubject

How does one Extract attachment of an e-mail from outlook with partly variable subject in Python?


It is required to extract an attached CSV file from an e-mail and save it in Python having received an e-mail of which the subject is partly variable but the fixed part of the e-mail subject is: e-mail statement [date of today in format dd/mm/yy]. Also, the subject has a variable part with a lot of random numbers. One had tried the following:

import glob
import win32com.client as win32
from datetime import date

Date_fmt2 = (date.today()).strftime("%d/%m/%y")

outlook = win32.Dispatch('outlook.application').GetNamespace("MAPI")
folder = outlook.Folders.Item(1).Folders.Item("Inbox").Folders.Item("Statements")
messages = folder.Items

for message in messages:
        if message.Subject == glob.glob(str('e-mail statement ' + Date_fmt2 + '*')):
               attachment = message.Attachments.Item(1)
               attachment.SaveAsFile('C:\\...\\Statement ' + Date_fmt2 + '.csv')

One thought the glob.glob part would solve the variable name, but it seemingly returned an empty value. Does anybody know how to do this?

Thanks in advance!


Solution

  • If the problem is with the glob.glob you chould try "startswith"

    if message.Subject.startswith('e-mail statement ' + Date_fmt2):
        attachment = message.Attachments.Item(1)
        attachment.SaveAsFile('C:\\...\\Statement ' + Date_fmt2 + '.csv')
    

    This is only correct if the variable part is on the end. https://www.w3schools.com/python/ref_string_startswith.asp