经过多次搜索后,我无法找到如何使用smtplib.sendmail发送给多个收件人.问题是每次发送邮件时邮件标题似乎包含多个地址,但事实上只有第一个收件人才会收到电子邮件.
问题似乎是email.Message模块期望与smtplib.sendmail()函数不同的东西.
简而言之,要发送给多个收件人,您应将标头设置为逗号分隔的电子邮件地址字符串.但该sendmail()参数to_addrs应该是电子邮件地址列表.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib
msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me@example.com"
msg["To"] = "malcom@example.com,reynolds@example.com,firefly@example.com"
msg["Cc"] = "serenity@example.com,inara@example.com"
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
smtp.quit()
Run Code Online (Sandbox Code Playgroud) 我无法看到我在哪里出错,我希望有人能发现问题.我想发一封电子邮件到多个地址; 但是,它只将它发送到列表中的第一个电子邮件地址,而不是两者.这是代码:
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")
Run Code Online (Sandbox Code Playgroud)
有没有人遇到过这个错误?
感谢您的时间.