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

2024-05-12 21:58:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

电子邮件工作,我在Juypter上安装,运行python3,从Outlook发送电子邮件。你知道吗

我的代码在下面。这个邮件.发件人姓名是我要从用户的Outlook帐户中提取名称的部分。在VBA中,这相当于使用应用程序.用户名你知道吗

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

所以我希望邮件正文是:

Dear All,

The latest version of the Report is attached in PDF format.

Kind Regards

Bob Smith

任何帮助,非常感谢。你知道吗

更新
通过将来自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()

Tags: ofthebrreportattachmentisversion电子邮件
1条回答
网友
1楼 · 发布于 2024-05-12 21:58:00

您可以:

  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

相关问题 更多 >