如何使用 python smtplib 向多个收件人发送电子邮件? [英] How to send email to multiple recipients using python smtplib?

查看:82
本文介绍了如何使用 python smtplib 向多个收件人发送电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过大量搜索,我无法找到如何使用 smtplib.sendmail 发送给多个收件人.问题是每次发送邮件时,邮件标题似乎都包含多个地址,但实际上只有第一个收件人会收到电子邮件.

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.

问题似乎在于 电子邮件.Message 模块需要与 smtplib.sendmail() 函数.

The problem seems to be that the email.Message module expects something different than the smtplib.sendmail() function.

简而言之,要发送给多个收件人,您应该将标题设置为以逗号分隔的电子邮件地址字符串.sendmail() 参数 to_addrs 但是应该是电子邮件地址列表.

In short, to send to multiple recipients you should set the header to be a string of comma delimited email addresses. The sendmail() parameter to_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆