0

I am trying to scan my outlook inbox based on subject and sender email and then trying to download any attached files locally in a specific location.

This code currently runs forever without detecting an email with the desired sender address and subject.

import win32com.client
import re

# set up connection to outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst()
while True:
  try:
    current_sender = str(message.Sender).lower()
    current_subject = str(message.Subject).lower()
    if re.search('The Subject I am scanning for',current_subject) != None and re.search('the sender email address to scan for',current_sender) != None:
      print(current_subject) 
      print(current_sender)  
      attachments = message.Attachments
      attachment = attachments.Item(1)
      attachment_name = str(attachment).lower()
      attachment.SaveASFile("Y:"+"\\" +"STRATEGIES"+"\\" + attachment_name)
    else:
      pass
    message = messages.GetNext()
  except:
    message = messages.GetNext()
exit

Ideally, once the download of the attachemnt of the specific email is comepleted, the email would be placed in my archive folder which is in index 39.

daniel
  • 37
  • 2
  • 9

1 Answers1

0

Firstly, do not loop through all messages in a fodler - use Items.FindFirst/FindsNext or Items.Restrict.

Secondly, MailItem.Sender is an object, not a string. When you cast it to a string, it gets converted using the default property (which is Name). What you want is MailItem.SenderEmailAddress.

In the future, you really need to step through your code and look at the values of the variables to see if they are what you expect.

Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78