Python自动化Outlook电子邮件: change sender or default reply-to address

标签 python email winapi outlook

我使用的代码类似于 Steve Townsend这个问题的答案:Send Outlook Email Via Python? 通过运行 python 脚本发送电子邮件。如何编辑默认回复地址,以便当有人回复自动电子邮件时,该电子邮件将被发送到特定地址?或者,我可以修改发送电子邮件的地址吗?我尝试修改 Msg.SentOnBehalfOfName 属性,但没有成功。请注意,该地址是别名,因此我无法登录 Outlook 中的帐户。

import win32com.client

def send_mail_via_com(text, subject, recipient, profilename="Outlook2003"):
    s = win32com.client.Dispatch("Mapi.Session")
    o = win32com.client.Dispatch("Outlook.Application")
    s.Logon(profilename)

    Msg = o.CreateItem(0)
    Msg.To = recipient

    Msg.CC = "moreaddresses here"
    Msg.BCC = "address"

    Msg.Subject = subject
    Msg.Body = text

    attachment1 = "Path to attachment no. 1"
    attachment2 = "Path to attachment no. 2"
    Msg.Attachments.Add(attachment1)
    Msg.Attachments.Add(attachment2)

    Msg.Send()

最佳答案

您可以尝试以下代码来自由选择发件人地址和收件人地址。

import win32com.client as win32

def send_mail():
    outlook_app = win32.Dispatch('Outlook.Application')

    # choose sender account
    send_account = None
    for account in outlook_app.Session.Accounts:
        if account.DisplayName == '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f586909b919087b59d9a8198949c99db969a98" rel="noreferrer noopener nofollow">[email protected]</a>':
            send_account = account
            break

    mail_item = outlook_app.CreateItem(0)   # 0: olMailItem

    # mail_item.SendUsingAccount = send_account not working
    # the following statement performs the function instead
    mail_item._oleobj_.Invoke(*(64209, 0, 8, 0, send_account))

    mail_item.Recipients.Add('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd8f989e98948d94989389bd92888991929296d39e9290" rel="noreferrer noopener nofollow">[email protected]</a>')
    mail_item.Subject = 'Test sending using particular account'
    mail_item.BodyFormat = 2   # 2: Html format
    mail_item.HTMLBody = '''
        <H2>Hello, This is a test mail.</H2>
        Hello Guys. 
        '''

    mail_item.Send()


if __name__ == '__main__':
    send_mail()

感兴趣的话可以引用这个case .

关于Python自动化Outlook电子邮件: change sender or default reply-to address,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59618725/

相关文章:

python - Python3中中断的shell

python - 如果键,值对存在于字典中跳过python

ruby-on-rails - Rails 3.0 发送邮件安全最佳实践

php - 使用 wp_mail() 发送 HTML 电子邮件时,CSS 将不起作用

c++ - 将结构从一个进程转移到另一个进程的最佳方法?

python - Elastic Beanstalk 从 shell SSH 连接到 RDS

python - 如何从亚马逊产品页面中提取 asin

python - 从我的域发送电子邮件还是从管理员 Google 帐户发送电子邮件?

c++ - 在 C++ 程序之间发送数据的基本命名管道?

windows - 如何枚举所有连接的 USB 设备的设备路径?