在 python 3 中更改发件人帐户 ms outlook

Change sender account ms outlook in python 3

我在 MS Outlook 中有 2 个帐户('user1@test.com' - 默认配置文件,'user2@test.com')并且我正在尝试使用非默认帐户通过 python 发送消息。这是我的代码:

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()

Outlook 从帐户 'user1@test.com' 发送,而不是从 'user2@test.com'。如何更改帐号?

MailItem.SendUsingAccount property allows setting an Account 对象代表要发送 MailItem 的帐户。

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()