Search code examples
python-3.xoutlookwin32com

How to iterate through emails and their attachments Python win32


I'm trying to find all emails sent to specific person ('Andrew' for demo purposes) and then to find attachment in each of this mail that contains string in its name (there are multiple attachments added to each mail).

Here is the code:

peopleInitials = ['XXX','YYY', 'ZZZ']
checkText = 'Andrew'
listalen = len(peopleInitials)

for message in messages:
     k = 0
     currentText = message.To     
     if checkText in currentText:
          for att in message.Attachments:
               attachmentName = att.FileName
               while k < listalen:
                    if peopleInitials[k] in attachmentName:
                         print('Atachment exists')
                         print(attachmentNames)
                    else: 
                         print('Attachment does not exist')
                         print(attachmentNames)
                    k = k + 1

It works partially- it iterates through e-mails and when it finds one addressed to Andrew it checks if attachment name contains 'XXX', 'YYY' or ''ZZZ. However it only checks one attachment for every e-mail and does not iterate through all its attachments. What am I doing wrong? Many thanks in advance

Using Outlook2016, Python 3.7 and win32com


Solution

  • It turned out that script actually does iterate through all attachments but after checking first file

    k = listalen 
    

    so it doesn't check other files. It works with every first attachment because k is set to 0 when script takes another message. So the only thing that I had to do was to add:

    k = 0
    

    before:

    while k < listalen: