问题
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()
回答1:
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.
回答2:
Recipients in the standard header must be separated by commas, not semicolons. I blame Microsoft Outlook for leading people to believe otherwise.
回答3:
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)
回答4:
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)
回答5:
Alternatively
recipient = ', '.join(recipient.split('; '))
if your recipients are a string of semicolon separated addresses.
来源:https://stackoverflow.com/questions/8995445/why-cant-i-send-emails-to-multiple-recipients-with-this-script