Python不向多个地址发送电子邮件

时间:2013-12-11 02:28:26

标签: python email smtp gmail smtplib

我无法看到我在哪里出错,我希望有人能发现问题。我想发一封电子邮件到多个地址;但是,它只将它发送到列表中的第一个电子邮件地址,而不是两者。这是代码:

import smtplib
from smtplib import SMTP

recipients = ['example1@gmail.com', 'example2@example.com']

def send_email (message, status):
    fromaddr = 'from@gmail.com'
    toaddrs = ", ".join(recipients)
    server = SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('example_username', 'example_pw')
    server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
    server.quit()

 send_email("message","subject")

之前有没有人遇到此错误?

感谢您的时间。

3 个答案:

答案 0 :(得分:9)

尝试使用此代码,不使用您的加入:

import smtplib
from smtplib import SMTP

recipients = ['example1@gmail.com', 'example2@example.com']

def send_email (message, status):
    fromaddr = 'from@gmail.com'
    server = SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('example_username', 'example_pw')
    server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
    server.quit()

 send_email("message","subject")

希望它有所帮助!

答案 1 :(得分:6)

   import smtplib

   from email.mime.text import MIMEText

   s = smtplib.SMTP('xxx.xx')

   msg = MIMEText("""body""")
   sender = 'xx.xx.com'

   recipients = ['example1@gmail.com', 'example2@example.com']

   msg['Subject'] = "test"
   msg['From'] = sender
   msg['To'] = ", ".join(recipients)
   s.sendmail(sender, recipients, msg.as_string())

答案 2 :(得分:5)

更改

toaddrs = ", ".join(recipients)

toaddrs = recipients

server.sendmail(fromaddr, toaddrs, ...)

希望toaddrs成为电子邮件地址的列表。 (或者,当然,只需使用recipients代替toaddrs。)