基于这个例子,我制作了以下函数:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(host, port, user, pwd, recipients, subject, body, html=None, from_=None):
""" copied and adapted from
https://dev59.com/HWkw5IYBdhLWcg3wGGm8
returns None if all ok, but if problem then returns exception object
"""
PORT_LIST = (25, 587, 465)
FROM = from_ if from_ else user
TO = recipients if isinstance(recipients, (list, tuple)) else [recipients]
SUBJECT = subject
TEXT = body.encode("utf8") if isinstance(body, unicode) else body
HTML = html.encode("utf8") if isinstance(html, unicode) else html
if not html:
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
else:
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = ", ".join(TO)
part1 = MIMEText(TEXT, 'plain', "utf-8")
part2 = MIMEText(HTML, 'html', "utf-8")
msg.attach(part1)
msg.attach(part2)
message = msg.as_string()
try:
if port not in PORT_LIST:
raise Exception("Port %s not one of %s" % (port, PORT_LIST))
if port in (465,):
server = smtplib.SMTP_SSL(host, port)
else:
server = smtplib.SMTP(host, port)
server.ehlo()
if port in (587,):
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
except Exception, ex:
return ex
return None
如果您只传递
body
参数,则会发送纯文本邮件,但如果您同时传递
html
和
body
参数,则会发送html格式的电子邮件(对于不支持html / mime类型的电子邮件客户端,会回退到文本内容)。
示例用法:
ex = send_email(
host = 'smtp.gmail.com'
, port = 587
, user = "xxx@gmail.com"
, pwd = "xxx"
, from_ = 'xxx@gmail.com'
, recipients = ['yyy@gmail.com']
, subject = "Test from python"
, body = "Test from python - body"
)
if ex:
print("Mail sending failed: %s" % ex)
else:
print("OK - mail sent"
顺便提一句,如果你想使用Gmail作为测试或生产SMTP服务器,请启用较不安全的应用程序的临时或永久访问权限: