如何在电子邮件正文中输入发件人姓名

时间:2019-06-19 13:38:08

标签: python outlook

我正在尝试设置一个脚本来发送电子邮件,并且我想将发件人姓名(取决于谁运行脚本)添加到电子邮件正文中。

发送电子邮件有效,我在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 RemorseEugene 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()

1 个答案:

答案 0 :(得分:1)

您可以:

  1. 使用NameSpace.CurrentUser属性,将当前登录用户的显示名称作为Recipient对象。
      Sub DisplayCurrentUser()  
        Dim myNamespace As Outlook.NameSpace 
        Set myNameSpace = Application.GetNameSpace("MAPI") 
        MsgBox myNameSpace.CurrentUser.Name  
      End Sub
  1. 如果已设置,则可以使用MailItem.SendUsingAccount属性,该属性返回一个Account对象,该对象表示要在其中发送MailItem的帐户。
     MailItem.SendUsingAccount.DisplayName
相关问题