1

我正在尝试使用以下代码向两个用户 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())
4

1 回答 1

3

将函数组织成更可重用的形式:

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 ------------
于 2013-08-30T04:10:02.563 回答