Python 不向多个地址发送电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20509427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Not Sending Email To Multiple Addresses
提问by Sam Perry
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 = ['[email protected]', '[email protected]']
def send_email (message, status):
fromaddr = '[email protected]'
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.
感谢您的时间。
采纳答案by Sergio Ayestarán
Try to use this code, without your join:
尝试使用此代码,无需您的加入:
import smtplib
from smtplib import SMTP
recipients = ['[email protected]', '[email protected]']
def send_email (message, status):
fromaddr = '[email protected]'
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!
希望能帮助到你!
回答by unutbu
Change
改变
toaddrs = ", ".join(recipients)
to
到
toaddrs = recipients
since
自从
server.sendmail(fromaddr, toaddrs, ...)
expects toaddrsto be a listof email addresses. (Or, of course, just use recipientsin place of toaddrs.)
期望toaddrs是电子邮件地址列表。(或者,当然,只是使用recipients代替toaddrs。)
回答by Tharanga Abeyseela
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('xxx.xx')
msg = MIMEText("""body""")
sender = 'xx.xx.com'
recipients = ['[email protected]', '[email protected]']
msg['Subject'] = "test"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

