首页 > 解决方案 > Create a for loop that generates individual emails with html dataframe for each unique recipient

问题描述

I want to create a for loop that creates individual emails with html dataframe for each unique recipient (using the first column).

the dataframe looks like this:

dataframe

Expected output:

Email one

Email two

My current code:

for index, row in df.iterrows():
email = (row['Email Address'])
subject = (row['Subject'])
table = df.iloc[:, 2:].to_html(index = False)
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = subject

newMail.HTMLbody = ( '''
<html>
<head>
</head>
    <body>
        <p>Hi All,</p>
        <p>{TABLE}</p>
        <p>Best Regards,</p>
    </body>
</html>'''.format(TABLE = table))

newMail.To = email
newMail.display()

标签: pythonpandas

解决方案


要按唯一电子邮件对表格进行分组,您需要使用 groupby:

grp = df.groupby('email') #group data by email
sent_mail = [] #store emails to which messages have been sent here
for index, row in df.iterrows():
    if row['email'] in sent_mail: #check if mail has already been sent to prevent sending multile mails
        pass
    else:
        email = (row['email'])
        sent_mail.append(email)
        subject = (row['subject'])
        table = grp.get_group(email).to_html(index = False)
        olMailItem = 0x0
        obj = win32com.client.Dispatch("Outlook.Application")
        newMail = obj.CreateItem(olMailItem)
        newMail.Subject = subject

        newMail.HTMLbody = ( '''
        <html>
        <head>
        </head>
            <body>
                <p>Hi All,</p>
                <p>{TABLE}</p>
                <p>Best Regards,</p>
            </body>
        </html>'''.format(TABLE = table))

        newMail.To = email
        newMail.display()

推荐阅读