E Falcon E Falcon - 1 year ago 248
Python Question

Replying To email via Outlook in Python

I am trying to reply to emails with a keyword in the subject but I need to do it all through outlook. My current code works decently but it would be better if it could reply directly instead of creating a new message.

Hopefully this is the right place to ask this :)

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

inbox = outlook.GetDefaultFolder(6)
def check_mail():
global message
messages = inbox.Items
message = messages.GetLast()
if (message.subject.find('@Bot') != -1 and message.unread and whtlist.find(message.SenderName)!= -1 ):
return 1
return 0

def Read_mail():
global message
global ACTIVE
body_content = message.body
print (body_content)
for att in message.Attachments:
att.SaveAsFile(os.getcwd() + '\\new.xlsx')
except :
print(bcolors.WARNING+'No Attachment Found'+bcolors.OKGREEN)
Msg = o.CreateItem(0)
Msg.To = message.SenderEmailAddress
print(bcolors.FAIL+'Reply sent to: {}'.format(message.SenderEmailAddress+bcolors.OKGREEN))
Msg.Subject = 'Autoreply'
Msg.Body = 'I see you {}.\n\nTesting\n-Bot'.format(message.SenderName)

Answer Source

Do not use Items.GetLast - it is not guaranteed to return the last received email. The Items collection is not sorted in any particular way unless you explicitly call Items.Sort. In your particular case, use Items.Restrict or Items.Find/FindNext to find the message based on your criteria (unread, subject contains a particular word, etc.).

To get a reply, call MailItem.Reply instead of Application.CreateItem - it will return the new MailItem object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download