如何使用python smtplib将邮件发送给多个收件人? [英] How to send email to multiple recipients using python smtplib?
问题描述
经过多次搜索,我找不到如何使用smtplib.sendmail发送给多个收件人。问题是每次发送邮件时,邮件头将显示为包含多个地址,但实际上只有第一个收件人才能收到邮件。
问题似乎这是 email.Message
模块期望与 smtplib.sendmail()
功能。
简而言之,要发送给多个收件人,您应该设置标题作为一串逗号分隔的电子邮件地址。 sendmail()
参数 to_addrs
但是应该是一个电子邮件地址列表。
from email.MIMEMultipart import MIMEMultipart
/ pre>
from email.MIMEText import MIMEText
import smtplib
msg = MIMEMultipart()
msg [Subject] =示例
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()
解决方案这个真的很好用,我花了很多时间尝试多种变体。 p>
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP(' smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText(body)
sender ='me@example.com'
recipient = ['john.doe @ example.com','john.smith@example.co.uk']
msg ['Subject'] =subject line
msg ['From'] = sender
msg [ 'to'] =,.join(recipient)
s.sendmail(发件人,收件人,msg.as_string())
After much searching I couldn't find out how to use smtplib.sendmail to send to multiple recipients. The problem was every time the mail would be sent the mail headers would appear to contain multiple addresses, but in fact only the first recipient would receive the email.
The problem seems to be that the
email.Message
module expects something different than thesmtplib.sendmail()
function.In short, to send to multiple recipients you should set the header to be a string of comma delimited email addresses. The
sendmail()
parameterto_addrs
however should be a list of email addresses.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()
解决方案This really works, I spent a lot of time trying multiple variants.
import smtplib from email.mime.text import MIMEText s = smtplib.SMTP('smtp.uk.xensource.com') s.set_debuglevel(1) msg = MIMEText("""body""") sender = 'me@example.com' recipients = ['john.doe@example.com', 'john.smith@example.co.uk'] msg['Subject'] = "subject line" msg['From'] = sender msg['To'] = ", ".join(recipients) s.sendmail(sender, recipients, msg.as_string())
这篇关于如何使用python smtplib将邮件发送给多个收件人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!