【问题标题】:Python send emails with corresponding attachmentsPython 发送带有相应附件的电子邮件
【发布时间】:2020-08-27 20:33:28
【问题描述】:

我有一个包含 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)

【问题讨论】:

    标签: python class outlook email-attachments


    【解决方案1】:

    您需要在电子邮件中引用文件名,因此请切换到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)
    

    【讨论】:

    • 谢谢!我用电子邮件和文件创建了一个字典,但是当我编辑上面的代码时,它显示“文件未定义”。有什么想法吗?你能演示一下我上面的代码中使用的“for”循环吗?
    猜你喜欢
    • 2014-11-09
    • 2017-02-04
    • 2019-11-21
    • 2015-09-09
    • 2020-09-16
    相关资源
    最近更新 更多