我正在尝试使用以下代码向两个用户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())
答案 0 :(得分:2)
将功能组织为更可重复使用的形式:
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 ------------