Pergunta

Why can't I send emails to multiple recipients with this script?

I get no errors nor bouncebacks, and the first recipient does receive the email. None of the others do.

The script:

#!/usr/bin/python
import smtplib

SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587

recipient = 'email@domain.com; email2@domain.com;'
sender = 'me@gmail.com'
subject = 'the subject'
body = 'the body'
password = "password"
username = "me@gmail.com"

body = "" + body + ""

headers = ["From: " + sender,
           "Subject: " + subject,
           "To: " + recipient,
           "MIME-Version: 1.0",
           "Content-Type: text/html"]
headers = "\r\n".join(headers)

session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

session.ehlo()
session.starttls()
session.ehlo
session.login(username, password)

session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
Foi útil?

Solução

Semicolons are not the correct separator for addresses in recipient headers. You must use commas.

EDIT: I see now that you are using the library incorrectly. You're supplying a string which will always be interpreted as a single address. You must supply a list of addresses to send to multiple recipients.

Outras dicas

Recipients in the standard header must be separated by commas, not semicolons. I blame Microsoft Outlook for leading people to believe otherwise.

You can, just put the emails in an array, and loop through the array for each email as in: (my python is rusty... so forgive my syntax)

foreach recipient in recipients
    headers = ["From: " + sender, "Subject: " + subject, "To: " + recipient, "MIME-Version: 1.0",  "Content-Type: text/html"]
    headers = "\r\n".join(headers)
    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)

Change this in your code:

recipient = ['email@domain.com','email2@domain.com']

headers = ",".join(headers)

session.sendmail(sender, recipient.split(","), headers + "\r\n\r\n" + body)

Alternatively

recipient = ', '.join(recipient.split('; '))

if your recipients are a string of semicolon separated addresses.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top