将函数组织成更可重用的形式:
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 ------------