0

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
        else:
            return 0

    def Read_mail():
        global message
        global ACTIVE
        body_content = message.body
        print(bcolors.WARNING+'\n______________________________________________________________________\n'+bcolors.OKGREEN)
        print (body_content)
        print(bcolors.WARNING+'\n______________________________________________________________________\n'+bcolors.OKGREEN)
        for att in message.Attachments:
            break
        try:
            att.SaveAsFile(os.getcwd() + '\\new.xlsx')
            print(os.getcwd())
        except :
            print(bcolors.WARNING+'No Attachment Found'+bcolors.OKGREEN)
        message.unread=False
        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)
        Msg.Send()
E Falcon
  • 15
  • 2
  • 6

1 Answers1

0

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.

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