简体   繁体   中英

Using a loop to send customized emails to multiple recipients in Python

I am writing code to send customized emails to multiple recipients using the same html template. The code extracts information from a csv file.

However, am unable to loop through the recipients to send them the email one by one. This is what I have:

email_list = [abc@gmail.com, def@gmail.com, ghi@gmail.com]

email['from'] = 'Zoya Aqib'
for recipient in email_list:
    email['to'] = recipient
email['subject'] = 'Corporate Rating Quiz'


for index,row in df.iterrows():
    email.set_content(html.substitute({'name': row['First Name'],'score': row['Score']}))
    with smtplib.SMTP(host='smtp.gmail.com',port=587) as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.login('me@gmail.com','mypassword')
        smtp.send_message(email)
    print('all done!')

But I am getting this error "ValueError: There may be at most 1 to headers in a message"

How do I loop over the recipients while customizing the template as shown above?

Thanks in advance!

I guess its because you haven't stored your email addresses as strings. Just enclose them in quotes and its should work.

You can't send message to multiple recipients at once. I guess you should just send messages separately.

Since you're setting email['to'] multiple times, you should have just replaced the header and send message to the last address, but it's not what actually happened. So IDK what the email is, but here is the solution that will probably work in your case:

email_list = ['abc@gmail.com', 'def@gmail.com', 'ghi@gmail.com']

email['from'] = 'Zoya Aqib'
email['subject'] = 'Corporate Rating Quiz'


for index,row in df.iterrows():
    email.set_content(html.substitute({'name': row['First Name'],'score': row['Score']}))
    with smtplib.SMTP(host='smtp.gmail.com',port=587) as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.login('me@gmail.com','mypassword')
        for recipient in email_list:
            if 'to' in email:
                del email['to'] 
            email['to'] = recipient
            smtp.send_message(email)
    print('all done!')

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