[英]Python : How to send mails using outlook and attach files
我有一個帶有 3 個電子郵件地址的 python 數組:
email_group = df.EMAIL.unique()
test@test.com
test1@test.com
test2@test.com
如何遍歷電子郵件數組,將第一個電子郵件地址分配給“mail.To”字段並發送? 然后循環到第二個電子郵件地址並發送,最后使用數組中的最終地址發送第三個電子郵件。
最終結果:我需要使用循環向數組中的每個地址發送一封電子郵件。
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'POPULATED FROM ARRAY LOOP'
mail.Subject = 'Report'
mail.Body = """Report is attached."""
mail.Send()
選項 1:使用類
email_addresses = ['test@test.com', 'test1@test.com', 'test2@test.com']
class EmailsSender:
def __init__(self):
self.outlook = win32.Dispatch('outlook.application')
def send_email(self, to_email_address, attachment_path):
mail = self.outlook.CreateItem(0)
mail.To = to_email_address
mail.Subject = 'Report'
mail.Body = """Report is attached."""
if attachment_path:
mail.Attachments.Add(Source=attachment_path, Type=olByValue)
mail.Send()
def send_emails(self, email_addresses, attachment_path=None):
for email in email_addresses:
self.send_email(email, attachment_path)
attachment_path = 'Enter report path here'
email_sender = EmailsSender()
email_sender.send_emails(email_addresses, attachment_path)
選項 2:使用函數
outlook = win32.Dispatch('outlook.application')
def send_email(outlook, to_email_address, attachment_path):
mail = outlook.CreateItem(0)
mail.To = to_email_address
mail.Subject = 'Report'
mail.Body = """Report is attached."""
if attachment_path:
mail.Attachments.Add(Source=attachment_path, Type=olByValue)
mail.Send()
attachment_path = 'Enter report path here'
for email in email_addresses:
send_email(outlook, email_addresses)
選項 3:就這樣
email_addresses = ['test@test.com', 'test1@test.com', 'test2@test.com']
outlook = win32.Dispatch('outlook.application')
attachment_path = 'Enter report path here'
for email in email_addresses:
mail = outlook.CreateItem(0)
mail.To = email
mail.Subject = 'Report'
mail.Body = """Report is attached."""
mail.Attachments.Add(Source=attachment_path, Type=olByValue)
mail.Send()
如果我理解你的問題,你可以簡單地在你的地址列表上使用for
循環
emails = ['test@test.com', 'test1@test.com', 'test2@test.com']
outlook = win32.Dispatch('outlook.application')
for email in emails:
mail = outlook.CreateItem(0)
mail.To = email
mail.Subject = 'Report'
mail.Body = """Report is attached."""
mail.Send()
我認為是這樣的:
emails = [
'test@test.com',
'test1@test.com',
'test2@test.com'
]
for email in emails:
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = email
mail.Subject = 'Report'
mail.Body = """Report is attached."""
mail.Send()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.