我有来自不同地方的代码我的模板,以便在我的各种脚本中发送电子邮件:
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"
,它会得到我的地址。
谢谢!
答案 0 :(得分:0)
The CurrentUser property of the Namespace or Account class allows to get the display name of the currently logged-on user as a Recipient object. The Recipient class provides the Address property which returns a string representing the e-mail address of the Recipient.
In case of Exchange server you may need to call more properties and methods:
Finally, I'd recommend using the Recipients property of the MailItem class which returns a Recipients collection that represents all the recipients for the Outlook item. The Add method creates a new recipient in the Recipients collection.
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
Don't forget to call the Resolve or ResolveAll methods of the Recipient(s) class to get your recipients resolved against the address book.