运行下面的程序之前,需要使用pip install flask-mail安装电子邮件扩展包。
import os.path
from flask import Flask
from flask.ext.mail import Mail, Message
app = Flask(__name__)
#以126免费邮箱为例
app.config['MAIL_SERVER'] = 'smtp.126.com'
app.config['MAIL_PORT'] = 25
app.config['MAIL_USE_TLS'] = True
#如果电子邮箱地址是abcd@126.com,那么应填写abcd
app.config['MAIL_USERNAME'] = 'your own username of your email'
app.config['MAIL_PASSWORD'] = 'your own password of the username'
def sendEmail(From, To, Subject, Body, Html, Attachments):
'''To:must be a list'''
msg = Message(Subject, sender=From, recipients=To)
msg.body = Body
msg.html = Html
for f in Attachments:
with app.open_resource(f) as fp:
msg.attach(filename=os.path.basename(f), data=fp.read(),
content_type = 'application/octet-stream')
mail = Mail(app)
with app.app_context():
mail.send(msg)
if __name__ == '__main__':
#From填写的电子邮箱地址必须与前面配置的相同
From = '<your email address>'
#目标邮箱地址,可以替换为自己的QQ邮箱地址
To = ['<1234567@qq.com>']
Subject = 'hello world'
Body = 'Only a test.'
Html = '<h1>test test test.</h1>'
Attachments =['c:\\python35\\python.exe']
sendEmail(From, To, Subject, Body, Html, Attachments)