Python 3.7 smtplib sendmail sends only to first recipient in list

Question:

I’ve gone through many SO posts and smtplib documentation, everything seems to be correct, but mail is sent to only first recipient in the list

Note: I’m using Python3.7, I’ve tried from Python 2.6 also, In below case mail is getting delivered only to very first recipient in receiver

Below is my code:

import smtplib
from email.mime.text import MIMEText


sender='[email protected]'
receiver=['[email protected]', '[email protected]', '[email protected]']
msg = MIMEText("message")
msg['Subject'] = "Test Email"
msg['From'] = sender
msg['To'] = ",".join(receiver)

server = smtplib.SMTP("smtp.domain", 25)
sever.sendmail(sender, receiver, msg.as_string())
server.quit()
Asked By: Rohit Nimmala

||

Answers:

Instead of

sever.sendmail(sender, receiver, msg.as_string())

use

server.send_message(msg)

SMTP.send_message() is a method for sending email.message.Message objects which will use the sender and receiver specified in the Message object. In your case that would be the variable msg (MIMEText is a subclass of Message).

I don’t know why, I had a similar issue when using it the way you did. Probably because to_addrs are specified twice as as_string() adds it to the message body, what happens later I don’t know.

to_addrs in SMTP.sendmail() is described as: "A list of addresses to send this mail to. A bare string will be treated as a list with 1 address.", so that was fine.

Answered By: IamFr0ssT