After much searching I couldn't find out how to use smtplib.sendmail to send to multiple recipients. The problem was every time the mail would be sent the mail headers would appear to contain multiple addresses, but in fact only the first recipient would receive the email.
The problem seems to be that the email.Message
module expects something different than the smtplib.sendmail()
function.
In short, to send to multiple recipients you should set the header to be a string of comma delimited email addresses. The sendmail()
parameter to_addrs
however should be a list of email addresses.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me@example.com"
msg["To"] = "malcom@example.com,reynolds@example.com,firefly@example.com"
msg["Cc"] = "serenity@example.com,inara@example.com"
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
smtp.quit()
So actually the problem is that SMTP.sendmail and email.MIMEText need two different things.
email.MIMEText sets up the "To:" header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)
SMTP.sendmail, on the other hand, sets up the "envelope" of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.
So, what you need to do is COMBINE the two replies you received. Set msg['To'] to a single string, but pass the raw list to sendmail:
I do it like this:
I came up with this importable module function. It uses the gmail email server in this example. Its split into header and message so you can clearly see whats going on:
It only worked for me with send_message function and using the join function in the list whith recipients, python 3.6.
I figured this out a few months back and blogged about it. The summary is:
If you want to use smtplib to send email to multiple recipients, use
email.Message.add_header('To', eachRecipientAsString)
to add them, and then when you invoke the sendmail method,use email.Message.get_all('To')
send the message to all of them. Ditto for Cc and Bcc recipients.I use python 3.6 and the following code works for me