python flask web开发实战 flask-email

2019-07-05 11:13:02 浏览数 (1)

1 MAIL_SERVER localhost 电子邮件服务器的主机名或IP 地址 MAIL_PORT 25 电子邮件服务器的端口 MAIL_USE_TLS False 启用传输层安全(Transport Layer Security,TLS)协议 MAIL_USE_SSL False 启用安全套接层(Secure Sockets Layer,SSL)协议 MAIL_USERNAME None 邮件账户的用户名 MAIL_PASSWORD None 邮件账户的密码

2 import os

...

app.config['MAIL_SERVER'] = 'smtp.googlemail.com' app.config['MAIL_PORT'] = 587 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')

3 hello.py:初始化Flask-Mail from flask.ext.mail import Mail mail = Mail(app)

4 保存电子邮件服务器用户名和密码的两个环境变量要在环境中定义。如果你在Linux 或 Mac OS X 中使用bash,那么可以按照下面的方式设定这两个变量: (venv)

export MAIL_PASSWORD=<Gmail password> 微软Windows 用户可按照下面的方式设定环境变量: (venv)

set MAIL_PASSWORD=<Gmail password>

除了前面提到的环境变量MAIL_USERNAME 和MAIL_PASSWORD 之外,这个版本的程序还需要使 用环境变量FLASKY_ADMIN。Linux 和Mac OS X 用户可使用下面的命令添加: (venv)

set FLASKY_ADMIN=<Gmail username>

5 hello.py:电子邮件支持 from flask.ext.mail import Message app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]' app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin flasky@example.com' 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) mail.send(msg)

6

image.png

image.png

7 hello.py:异步发送电子邮件 from threading import Thread 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

0 人点赞