单账号:
import win32com.client as win32
def send_mail():
outlook = win32.Dispatch('Outlook.Application')
mail_item = outlook.CreateItem(0) # 0: olMailItem
mail_item.Recipients.Add('test@test.com')
mail_item.Subject = 'Mail Test'
mail_item.BodyFormat = 2 # 2: Html format
mail_item.HTMLBody = '''
Hello, This is a test mail.
Hello Guys.
'''
mail_item.Attachments.Add('<附件文件路径>')
mail_item.Send()
if __name__ == '__main__':
send_mail()
多账号:
def send_mail():
outlook_app = win32.Dispatch('Outlook.Application')
# choose sender account
send_account = None
for account in outlook_app.Session.Accounts:
if account.DisplayName == 'sender@hotmail.com':
send_account = account
break
mail_item = outlook_app.CreateItem(0) # 0: olMailItem
# mail_item.SendUsingAccount = send_account not working
# the following statement performs the function instead
mail_item._oleobj_.Invoke(*(64209, 0, 8, 0, send_account))
mail_item.Recipients.Add('receipient@qq.com')
mail_item.Subject = 'Test sending using particular account'
mail_item.BodyFormat = 2 # 2: Html format
mail_item.HTMLBody = '''
Hello, This is a test mail.
Hello Guys.
'''
mail_item.Send()
if __name__ == '__main__':
send_mail()
给多个地址发邮件:
import win32com.client as win32
import pythoncom
pythoncom.CoInitialize()
def send_mail(**kwargs):
outlook = win32.Dispatch('Outlook.Application')
reciList = ['user1@test.com','user2@test.com']
for i in range(len(reciList)):
mail_item = outlook.CreateItem(0) # 0: olMailItem
mail_item.Recipients.Add(reciList[i])
mail_item.Subject = 'Mail Test'
mail_item.BodyFormat = 2 # 2: Html format
mail_item.HTMLBody = '''
Hello, This is a test mail~~.
Hello Guys. '''
# mail_item.Attachments.Add('d:\doc\IT Info.xlsx')
mail_item.Send()
if __name__ == '__main__':
send_mail()