Search code examples
python-3.xoutlookpython-multithreadingwin32comoffice-automation

How to send and read mails from outlook through python via threads?


I am trying to read and send mails through outlook using python via threads. I am trying to use win32com.client along with pythoncom.

outlook         = win32.Dispatch("Outlook.Application")
mapi            = outlook.GetNamespace("MAPI")
inbox           = mapi.GetDefaultFolder(6)
messages        = inbox.Items
messages        = messages.Restrict("[ReceivedTime] >= '"+maintenance_date+"'")
.....
.....
.....
for message in messages:
    mail = message.ReplyAll()
    mail.To = mail.To
    mail.CC = mail.CC
    mail.Body = f"This is a reply!\nRegards\n{mail.Body}"
    mail.Save()
    mail.Send()

I don't seem to understand how to do this in a threaded environment as there many such replies.

I am expecting to do this in a threaded environment so that I can use the resources more efficiently.


Solution

  • Outlook uses a single-threaded apartment model and doesn't support calling properties and methods from multiple threads. Latest Outlook versions can throw an exception when such cases are detected.

    If you need to use multiple threads your choice is a low-level API on which Outlook is based on - Extended MAPI which allows running multiple threads. Or just consider using any third-party wrappers around that API such as Redemption where you could deal with multithreading.

    Also I've noticed the following piece of code where the To, Cc properties are set on the reply:

    for message in messages:
        mail = message.ReplyAll()
        mail.To = mail.To
        mail.CC = mail.CC
        mail.Body = f"This is a reply!\nRegards\n{mail.Body}"
        mail.Save()
        mail.Send()
    

    where the following lines of code don't make any sense:

    mail.To = mail.To
    mail.CC = mail.CC
    

    When you call the ReplyAll method recipients are set up automatically. Just try to click the corresponding button on the ribbon in Outlook and you will get a reply set with all recipient-related properties out of the box.