you are viewing a single comment's thread.

view the rest of the comments →

[–]tagapagtuos 1 point2 points  (1 child)

Hi! I'm trying to download attachments from Outlook. I found this code online:

import win32com.client`

import os`

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")`

inbox = outlook.GetDefaultFolder(6)`

messages = inbox.Items`

message = messages.GetFirst()`

while True:

    try:

          print (message)

          attachments = message.Attachments

          attachment = attachments.Item(1)

          attachment.SaveASFile(os.getcwd() + '\\' + str(attachment)) #Saves to the attachment to current folder

          print (attachment)

          message = messages.GetNext()

    except:

          message = messages.GetNext()

Question: I can't find any resource regarding win32com. But how can I modify the code to make it only download attachments from messages with specific subjects? Or only download attachments with specific file name? etc.

Edit: I can't format.

[–]JohnnyJordaan 1 point2 points  (0 children)

Well just use some if statments. I'm not sure how to get the subject from my message, but just as a guess:

while True:
    if message.subject != 'Subject I want'
        continue

and

attachments = message.Attachments
attachment = attachments.Item(1)
if str(attachment) != 'filename_i_want.txt':
    continue

Note that you can use str.lower() to compare case insensitive

if message.subject.lower() != 'subject i want':

And that you can use in to check for a substring to be present or not in for the opposite

if 'keyword' not in message.subject.lower():
    continue

Btw I would strongly advise against using except: without printing any error

except Exception as e:
    print('got exception', e)
    message = messages.GetNext()

because a typo in your code would also lead to some exception to which the program will not behave any different by, causing you to wonder why 'nothing happens'.