简体   繁体   中英

Python send emails with corresponding attachments

I have a desktop folder with 3 XLSX files: ID1.xlsx , ID2.xlsx , ID3.xlsx

I can use the following code to loop through a list of 3 email addresses and send individual emails to each address, but it attaches all XLSX files in the folder.

Expected Result: I want to attach ID1.xlsx to the first email and send, ID2.xlsx to the 2nd email and send, and finally ID3.xlsx to the 3rd email and send.

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)

You will need to reference the file name with email so switch to Dictionaries .

Example

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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