B-DK
B-DK

Reputation: 75

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.

Upvotes: 2

Views: 6979

Answers (2)

B-DK
B-DK

Reputation: 75

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 protected]":
                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()

Upvotes: 3

Eugene Astafiev
Eugene Astafiev

Reputation: 49395

There is no need to use these both properties at the same time in Outlook:

mail.SentOnBehalfOfName  =  accounts[1]
mail.SendUsingAccount  =  accounts[1]

The From field available in the Outlook UI corresponds to the MailItem.SendUsingAccount property which returns or sets an Account object that represents the account under which the MailItem is to be sent. This option is available when you have multiple accounts configured in Outlook.

The MailItem.SentOnBehalfOfName property returns a string, not an Account instance, where a string indicates the display name for the intended sender of the mail message. Be aware, the permission should be given to be able to send on behalf of another person in Exchange.

So, if you have got multiple accounts configured in Outlook you may go with the following line of code:

mail.SendUsingAccount  =  accounts[1]

Upvotes: 0

Related Questions