通过 win32com.clien 发送我的电子邮件

2024-04-27 19:03:59 发布

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

我从不同地方收集的代码中有一个模板,可以用我的各种脚本发送电子邮件:

import win32com.client

##################################################
##################################################
##################################################
##################################################
##################################################
#this is a mutipurpose email template

def email_template(recipient, email_subject, mail_body, attachment1, attachment2):
    Format = { 'UNSPECIFIED' : 0, 'PLAIN' : 1, 'HTML' : 2, 'RTF'  : 3}
    profile = "Outlook"
    #session = win32com.client.Dispatch("Mapi.Session")
    outlook = win32com.client.Dispatch("Outlook.Application")
    #session.Logon(profile)
    mainMsg = outlook.CreateItem(0)
    mainMsg.To = recipient
    mainMsg.BodyFormat = Format['RTF']

    #########################
    #check if there is a mail body
    try:
        mainMsg.Subject = email_subject
    except:
        mainMsg.Subject = 'No subject'

    #########################
    #check if there is a mail body
    try:
        mainMsg.HTMLBody = mail_body
    except:
        mainMsg.HTMLBody = 'No email body defined'

    #########################
    #add first attachement if available
    try:
        mainMsg.Attachments.Add(attachment1)
    except:
        pass

    #########################
    #add second attachement if available
    try:
        mainMsg.Attachments.Add(attachment2)
    except:
        pass

    mainMsg.Send()  #this line actually sends the email

工作完美。简单。但是我有一个小问题,我正在构建一个脚本,需要向用户发送电子邮件。使用此模板,如何获取用户outlook电子邮件?我的意思是像使用"me"这样它就会得到我的地址。

谢谢!!


Tags: 脚本client模板ifis电子邮件emailbody
1条回答
网友
1楼 · 发布于 2024-04-27 19:03:59

命名空间或Account类的CurrentUser属性允许获取当前登录用户的显示名称作为收件人对象。Recipient类提供Address属性,该属性返回表示收件人电子邮件地址的字符串。在

对于Exchange server,您可能需要调用更多属性和方法:

  1. 使用Recipient类的AddressEntry属性。在
  2. 调用AddressEntry类的GetExchangeUser方法,如果AddressEntry属于Exchange AddressList对象(如全局地址列表(GAL)并与Exchange用户相对应,则该方法返回表示AddressEntry的ExchangeUser对象。在
  3. 获取PrimarySmtpAddress属性值。返回表示ExchangeUser的主简单邮件传输协议(SMTP)地址的字符串。在

最后,我建议使用MailItem类的Recipients属性,该属性返回一个表示Outlook项的所有收件人的Recipients集合。Add方法在Recipients集合中创建一个新的收件人。在

 Sub CreateStatusReportToBoss()  
  Dim myItem As Outlook.MailItem  
  Dim myRecipient As Outlook.Recipient 
  Set myItem = Application.CreateItem(olMailItem) 
  Set myRecipient = myItem.Recipients.Add("Eugene Astafiev")
  myItem.Subject = "Status Report"  
  myItem.Display  
 End Sub

别忘了调用Recipient(s)类的Resolve或ResolveAll方法来根据地址簿解析收件人。在

相关问题 更多 >