Joel
Joel

Reputation: 99

Using Python smtplib to send to distribution lists

I'm using SMTPlib to automatically send out an email:

emailto = ['[email protected]','[email protected]']
emailfrom = "[email protected]"

msg = MIMEMultipart('related')
msg['Subject'] = currentdate + " Subject"
msg['From'] = emailfrom
msg['To'] = ", ".join(emailto)  

msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
msgAlternative.attach(msgText)

smtpObj = smtplib.SMTP('mail.email.com')
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.sendmail(emailfrom, emailto, msg.as_string())
smtpObj.quit()

When I use this code I get the email, with [email protected] in the "To:" line as well, but no one in [email protected] gets it. I've sent to distribution lists before with no problem, but this specific one will not work. It is a fairly large list (~100 recipients)

Upvotes: 2

Views: 1385

Answers (1)

VPfB
VPfB

Reputation: 17322

Errors may pass unnoticed, because you are not checking the result of .sendmail() when sending to multiple addresses.

This method will not raise an exception if it succeeds to send the email to at least one recipient.

The important part of the docs is:

This method will return normally if the mail is accepted for at least one recipient. Otherwise it will raise an exception. If this method does not raise an exception, it returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server.

Something like this should help to find the problem:

errors = smtpObj.sendmail(emailfrom, emailto, msg.as_string())
for recipient, (code, errmsg) in errors.items():
    # ... print or log the error ...

Upvotes: 1

Related Questions