Python 发送带有相应附件的电子邮件

Python send emails with corresponding attachments

我有一个包含 3 个 XLSX 文件的桌面文件夹:ID1.xlsxID2.xlsxID3.xlsx

我可以使用以下代码遍历 3 个电子邮件地址的列表并向每个地址发送单独的电子邮件,但它会附加文件夹中的所有 XLSX 文件。

预期结果: 我想将 ID1.xlsx 附加到第一封电子邮件并发送, ID2.xlsx 到第二封电子邮件并发送,最后 ID3.xlsx 到第三封邮件并发送。

email_addresses = ['test1@test.com', 'test2@test.com', 'test3@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 = r'C:\Users\Desktop\Test\*.xlsx'
email_sender = EmailsSender()
email_sender.send_emails(email_addresses, attachment_path)

您需要在电子邮件中引用文件名,因此切换到 Dictionaries

例子

email_addresses = {'test1@test.com': 'ID1.xlsx',
                   'test2@test.com': 'ID2.xlsx',
                   'test3@test.com': 'ID3.xlsx'
                   }

attachment_path = r'C:\Users\Desktop\Test'


for email, file in email_addresses.items():
    print(email, attachment_path + file)