I'm working with a python script to dynamically send HTML emails to 400 users using Amazon Simple Email Service. The script reads the emails addresses from an Excel file with openpyxl.
But the script is randomly crashing around 260 to 280 users while sending. My current workaround is to set the Excel file at the position where the script previously crashed then run it again. There is my code:
import email.utils
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart('alternative')
msg['From'] = sender_email
msg['Subject'] = 'Your email subject'
context = ssl.create_default_context()
server = smtplib.SMTP_SSL(smtp_server, port, context=context)
server.login(smtp_login, password)
for dest_email in email_list:
message_html = '<html><head><title></title></head><body>Dynamic content here...</body></html>'
message_plain = 'Content here...'
part1 = MIMEText(message_plain, 'plain')
part2 = MIMEText(message_html, 'html')
msg.attach(part1)
msg.attach(part2)
server.sendmail(sender_email, dest_email, msg.as_string())
server.close()
I tried catching exceptions during execution but I'm not getting much details about what's wrong here:
I've been looking around for some time but can't get my hands on the issue. Could you please help me figure this out? What am I doing wrong? Is there a header I need to reset after each successful email sent? Let me know if you need additional details. Thanks.
From the top of my head I would say that only the server.sendmail()
part should be inside the loop. Right now you seem to be re-sending a single e-mail (msg
), which gets new parts attached in each iteration, and that's what the error message says too.
Alternatively, if that does not work: re-create the entire object in the loop, so move the block starting with msg = ...
inside.