Yuri Molodyko
Yuri Molodyko

Reputation: 600

Change sender account ms outlook in python 3

I have 2 accounts in ms outlook ('[email protected]' - default profile ,'[email protected]') and i'm trying to sent a message by python using the non-default account. Here is my code:

Import win32com.client
app = win32com.client.Dispatch('Outlook.application')

mess = app.CreateItem(0)
mess.to = '[email protected]'
mess.subject = 'hi'
mess.SendUsingAccount = '[email protected]'
mess.Send()

And outlook sent from account '[email protected]', not from '[email protected]'. How to change an account?

Upvotes: 5

Views: 4800

Answers (2)

Marcos André
Marcos André

Reputation: 1

Try this line before Send. And delete mess.SendUsingAccount

mess.SentOnBehalfOfName = "[email protected]"  

Upvotes: 0

Eugene Astafiev
Eugene Astafiev

Reputation: 49397

The MailItem.SendUsingAccount property allows setting an Account object that represents the account under which the MailItem is to be sent.

import win32com.client

o = win32com.client.Dispatch("Outlook.Application")
oacctouse = None
for oacc in o.Session.Accounts:
    if oacc.SmtpAddress == "[email protected]":
        oacctouse = oacc
        break
Msg = o.CreateItem(0)
if oacctouse:
    Msg._oleobj_.Invoke(*(64209, 0, 8, 0, oacctouse))  # Msg.SendUsingAccount = oacctouse

if to:
    Msg.To = ";".join(to)
if cc:
    Msg.CC = ";".join(cc)
if bcc:
    Msg.BCC = ";".join(bcc)

Msg.HTMLBody = ""

Msg.Send()

Upvotes: 3

Related Questions