繁体   English   中英

Python:如何使用 Outlook 发送邮件并附加文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM