Search code examples
pythonloops

For each unique email found load all correlating attachments


I am trying to automatically create emails that include all associated attachments with the email. I have an excel document that is being referenced for the emails and attachments.

index = 0
counter = 0
for email in emails:
    mailItem = olApp.CreateItem(0)
    mailItem.Subject = 
    mailItem.BodyFormat = 1
    mailItem.Body = 
    mailItem.To = email
    counter = counter + 1

    for attachment in attachments:
        mailItem.Attachments.Add(attachment)
    index+=1
    mailItem.Display()

counter+=1

emails attachments
email 1 attach A
email 1 attach B
email 2 attach C
email 3 attach D

I thought that a while or if statement might be the answer but I can't seem to get it to work. I know that the code listed above will provide me four emails but it includes all attachments when it cycles through each of the email addresses. What I would like it to do is provide three email addresses with the first only including attach A and B. Email 2 only including attach C and Email 3 only including attach D.


Solution

  • Create a dictionary that maps each email to a list of attachments. Then when you have multiple attachments for an email, you can append them all to the same message instead of creating a new message.

    from collections import defaultdict
    
    attach_dict = {}
    for email, attachment in zip(emails, attachments):
        attach_dict.setdefault(email, []).append(attachment)
    
    for email, atts in attach_dict.items():
        mailItem = olApp.CreateItem(0)
        mailItem.Subject = "subject"
        mailItem.BodyFormat = 1
        mailItem.Body = "message body"
        mailItem.To = email
    
        for attachment in atts:
            mailItem.Attachments.Add(attachment)
        mailItem.Display()
    
    counter = len(attach_dict)