Boomshakalaka
Boomshakalaka

Reputation: 521

Send Outlook Emails with attachments in Python (pywin32)

I am trying to use the library pywin32 to write Outlook e-mails in Python. I have a dataframe that has some recipients' emails and attachment paths. I'd like to know how to add all attachments under each unique recipient?

print(my_df)

Receiver_Email             Attachment_Path                          HTMLBody
[email protected]         C:/Users/Desktop/Attachment1.pdf        HTMLBODY_1
[email protected]         C:/Users/Desktop/Attachment2.pdf        HTMLBODY_1
[email protected]         C:/Users/Desktop/Attachment3.pdf        HTMLBODY_1
[email protected]     C:/Users/Desktop/Attachment11.pdf       HTMLBODY_2
[email protected]     C:/Users/Desktop/Attachment22.pdf       HTMLBODY_2
[email protected]     C:/Users/Desktop/Attachment33.pdf       HTMLBODY_2

My coding is showing below:

for index, row in my_df.iterrows():
    outlook = client.Dispatch('Outlook.Application')
    mail = outlook.CreateItem(0)
    mail.To = row['Receiver_Email']
    mail.Subject = 'Greetings from Here!'
    mail.Body = 'Please find your attachment(s)'
    mail.Attachments.Add(row['Attachment_Path'])
    mail.HTMLBody = row['HTMLBODY']
    mail.Send()

However, this would send 3 emails to [email protected] and 3 emails to [email protected]. My expected outputs would be sending 2 emails total (1 for john and 1 for sean) with 3 attachments each.

Is there a way to do that? Thank you for the help!

Upvotes: 0

Views: 2686

Answers (1)

Q-man
Q-man

Reputation: 2209

Do a groupby on the email addresses, which creates unique dataframes, then iterate on the mail attachments. Something like this should work:

GB = my_df.groupby("Receiver_Email")
for ID , DF in GB:
    outlook = client.Dispatch('Outlook.Application')
    mail = outlook.CreateItem(0)
    mail.To = row['Receiver_Email']
    mail.Subject = 'Greetings from Here!'
    mail.Body = 'Please find your attachment(s)'
    for id , row in DF.iterrows():
        mail.Attachments.Add(row['Attachment_Path'])
    mail.Send()

Upvotes: 1

Related Questions