python - Python 自动 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 == 'sender@hotmail.com':
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('receipient@outlook.com')
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()
如果你感兴趣,可以参考这个案例。
推荐阅读
- machine-learning - 为什么我们应该在机器学习中使用 Lasso 而不是线性回归进行特征选择?
- java - Runtime.getRuntime().exec 命令失败,所有根活动的退出状态为 127
- spring-boot - springboot中使用@KafkaListener时,如何设置idleBetweenPolls
- python - 在python中格式化字典结构
- mysql - 嵌套连接的更新不适用于订单
- sorting - 有没有办法计算排序算法的进度?
- git - 是否有任何 git 托管允许跨存储库进行 PR?
- google-bigquery - 如何降低 Google BigQuery 费用?
- python - 使用 PyTorch 的交叉熵损失函数是否需要 One-Hot Encoding?
- php - 为什么这个 php 插件在下午 5 点之后仍在执行?