【发布时间】:2019-06-19 13:38:08
【问题描述】:
我正在尝试设置一个脚本来发送电子邮件,并且我想将发件人姓名(取决于谁运行脚本)添加到电子邮件正文。
电子邮件有效,我在 Juypter 上设置,运行 Python 3,从 Outlook 发送电子邮件。
我的代码如下。 mail.SenderName 是我想从用户的 Outlook 帐户中提取名称的部分。在 VBA 中,这相当于使用 Application.UserName
import win32com.client as win32
outlook = win32.Dispatch("outlook.application")
mail = outlook.CreateItem(0)
mail.To = "user@somewhere.com"
mail.Subject = "Report"
#Text for email
mail.HTMLBody = "Dear All,<br><br>" \
"The latest version of the Report is attached in PDF format.<br><br>" \
"Kind Regards <br><br>" \
mail.SenderName
attachment = filename
mail.Attachments.Add(attachment)
mail.Send()
所以我希望电子邮件正文是:
亲爱的,
报告的最新版本以 PDF 格式附上。
亲切的问候
鲍勃·史密斯
任何帮助,非常感谢。
更新
通过结合来自Error - Syntactical Remorse 和Eugene Astafiev 的响应以及更多搜索,我设法解决了这个问题。谢谢你的指导。
完整代码为:
outlook = win32.Dispatch("outlook.application")
mail = outlook.CreateItem(0)
mail.To = "user@somewhere.com"
mail.Subject = "Report"
sender = outlook.GetNamespace("MAPI").CurrentUser.Name
#Text for email
mail.HTMLBody = "Dear All,<br><br>" \
"The latest version of the Report is attached in PDF format.<br><br>" \
"Kind Regards <br><br>" \
f"{sender}"
attachment = filename
mail.Attachments.Add(attachment)
mail.Send()
【问题讨论】:
-
使用字符串格式。
f"Sent from {mail.SenderName}"之类的东西(在 Python2.7 中你需要我们%字符串格式)。 -
或者只是
str(mail.SenderName) -
f"{mail.SenderName}"行看起来正在尝试工作,但我认为它实际上无法从我的 Outlook 帐户中获取我的姓名。 (基本上我的名字应该是一个空格)