Python Not Sending Email To Multiple Addresses

走远了吗. 提交于 2019-11-29 20:02:35

问题


I can't see where i'm going wrong with this, I hope someone can spot the problem. I'd like to send an email to multiple addresses; however, it only sends it to the first email address in the list and not both. Here's the code:

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")

Has anyone came across this error before?

Thank you for your time.


回答1:


Try to use this code, without your join:

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")

Hope it helps!




回答2:


Change

toaddrs = ", ".join(recipients)

to

toaddrs = recipients

since

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

expects toaddrs to be a list of email addresses. (Or, of course, just use recipients in place of toaddrs.)




回答3:


   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())


来源:https://stackoverflow.com/questions/20509427/python-not-sending-email-to-multiple-addresses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!