Flask框架中用QQ邮箱发邮件

配置信息,看注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] =\
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
# 邮箱提供商服务器,这里是QQ邮箱
app.config['MAIL_SERVER'] = 'smtp.qq.com'
# 邮箱服务器端口(QQ邮箱的是465)
app.config['MAIL_PORT'] = 465
# 邮箱通讯协议,注意这里是SSL(选错了邮件发不出的)
app.config['MAIL_USE_SSL'] = True
# 发件邮箱
app.config['MAIL_USERNAME'] = '694244330@qq.com'
# 发件密码
app.config['MAIL_PASSWORD'] = 'tdjzzgfdiwgobehh'
# 拼接邮件的主题用,不是必选配置
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
# 发件邮箱和Mail_username的邮箱要一样
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <694244330@qq.com>'
# 收件邮箱
app.config['FLASKY_ADMIN'] = 'hsw_v5@163.com'
mail = Mail(app)

注意:上述配置项一个也不要少

发邮件方法

1
2
3
4
5
6
7
8
9
10
11
12
13
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
Donate comment here