pythonpython-3.xoutlookwin32comoffice-automation

Sending outlook email using win32com on python from a secondary mailbox account


I'm having an issue like this one

        outlook = win32com.client.Dispatch('outlook.application')
        accounts = win32com.client.Dispatch("outlook.Application").Session.Accounts
        print(accounts[1])
        mail = outlook.CreateItem(0)
        mail.SentOnBehalfOfName  =  accounts[1]
        mail.SendUsingAccount  =  accounts[1]
        mail.To = to
        mail.Subject = 'Subject TEST'
        mail.HTMLBody = emailBody
        mail.display()
        mail.Send()

if I comment mail.Send() the window that shows up will show everything correctly but if I send it, i'll get reply This message could not be sent. You do not have the permission to send the message on behalf of the specified user. which is obviously not true since if instead of sending directly and choose the exact same email from the dropdown menu in From, and then click SEND, it will send the email with no issues.


Solution

  • So with the help of @Eugene Astafiev and this post I fixed the issue like this:

            outlook = win32com.client.Dispatch('outlook.application')
            for account in outlook.Session.Accounts:
                if account.DisplayName == "email@email.om":
                    print(account)
                    mail = outlook.CreateItem(0)
                    mail._oleobj_.Invoke(*(64209, 0, 8, 0, account))
                    mail.To = to
                    mail.Subject = 'Support'
                    mail.HTMLBody = emailBody
                    #mail.display()
                    mail.Send()