如何将电子邮件发送给多个收件人? [复制]
Posted
技术标签:
【中文标题】如何将电子邮件发送给多个收件人? [复制]【英文标题】:how to send email to multiple recipients? [duplicate] 【发布时间】:2013-09-02 16:18:25 【问题描述】:我正在尝试使用以下代码向两个用户 ID 发送电子邮件,知道出了什么问题吗?如何发送给多个收件人?
def email1(body,subject):
print "In email1"
msg = MIMEText("%s" % body)
msg['Content-Type'] = "text/html; charset=UTF8"
msg['Subject'] = subject
s = SMTP('localhost',25)
s.sendmail('userid@company.com', ['userid1@company.com','userid2@company.com'],msg=msg.as_string())
【问题讨论】:
【参考方案1】:将函数组织成更可重用的形式:
from smtplib import SMTP
from email.mime.text import MIMEText
def send_email(body, subj, frm, to, host='localhost', port=25):
msg = MIMEText(body)
msg['Content-Type'] = 'text/html; charset=UTF8'
msg['Subject'] = subj
msg['From'] = frm
msg['To'] = ', '.join(to) if type(to) == list else to
smtp = SMTP(host, port)
smtp.sendmail(frm, to, msg=msg.as_string())
要使用内置 SMTP 服务器对其进行测试,请使用以下命令在端口 3000 上运行它:
python -msmtpd -n -c DebuggingServer localhost:3000
并发送一些电子邮件:
>>> send_email('Message', 'Spam', 'me@foo.com', ['u1@foo.com', 'u2@foo.com'], port=3000)
>>>
>>> send_email('Message', 'Spam', 'me@foo.com', 'u1@foo.com', port=3000)
>>>
你应该看到:
> python -msmtpd -n -c DebuggingServer localhost:3000
---------- MESSAGE FOLLOWS ----------
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Type: text/html; charset=UTF8
Subject: Spam
From: me@foo.com
To: u1@foo.com, u2@foo.com
X-Peer: 127.0.0.1
Message
------------ END MESSAGE ------------
---------- MESSAGE FOLLOWS ----------
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Type: text/html; charset=UTF8
Subject: Spam
From: me@foo.com
To: u1@foo.com
X-Peer: 127.0.0.1
Message
------------ END MESSAGE ------------
【讨论】:
以上是关于如何将电子邮件发送给多个收件人? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
有没有办法在 Python 的 Pandas 数据框中通过 SMTPLib 将电子邮件连接到多个收件人? [复制]
如何使用 python smtplib 向多个收件人发送电子邮件?
将多个收件人电子邮件和姓名附加到 EmailMultiAlternatives