outlookpython-3.6pywin32

Change sender account ms outlook in python 3


I have 2 accounts in ms outlook ('user1@test.com' - default profile ,'user2@test.com') 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 = 'user2@test.com'
mess.subject = 'hi'
mess.SendUsingAccount = 'user2@test.com'
mess.Send()

And outlook sent from account 'user1@test.com', not from 'user2@test.com'. How to change an account?


Solution

  • 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 == "user2@test.com":
            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()