Python 使用win32com.client向自己发送电子邮件

Python 使用win32com.client向自己发送电子邮件,python,outlook,win32com,Python,Outlook,Win32com,我从不同的地方收集了一个代码模板,用不同的脚本发送电子邮件: import win32com.client ################################################## ################################################## ################################################## ##########################################

我从不同的地方收集了一个代码模板,用不同的脚本发送电子邮件:

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电子邮件?我的意思是像只使用
“我”
,它就会得到我的地址

谢谢

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

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

  • 使用收件人类的属性
  • 调用AddressEntry类的方法,该类返回一个ExchangeUser对象,如果AddressEntry属于Exchange AddressList对象(如全局地址列表(GAL))并对应于Exchange用户,则该对象表示AddressEntry
  • 获取属性值。返回表示ExchangeUser的主简单邮件传输协议(SMTP)地址的字符串
  • 最后,我建议使用MailItem类的属性,该类返回一个Recipients集合,该集合表示Outlook项目的所有收件人。该方法在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类的Resolve或ResolveAll方法,以根据通讯簿解析收件人