使用flask发送邮件

####安装flask-mail
sudo pip install flask-mail

####设置环境变量
export MAIL_USERNAME=’XXXXX@qq.com’ #发送邮件的邮箱
export MAIL_PASSWORD=’password’ #发送邮件的邮箱密码

####使用flask-mail发送邮件
(venv)zhangkeyuan@opsnotes:~/Test/flask » cat flask-mail.py

#!/bin/env python
#-*- coding:utf-8 -*-
from flask import Flask, render_template
from flask.ext.mail import Mail,Message
import os


app = Flask(__name__)
####SMTP server config
app.config['MAIL_SERVER'] = 'smtp.qq.com' #电子邮件服务器的地址
app.config['MAIL_PORT'] = '25'   #邮箱服务器的端口
app.config['MAIL_USE_TLS'] = True  #启用安全传输
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')  #邮件账户用户名,已定义环境变量
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')  #邮件账密码,已定义环境变量


mail = Mail(app)

@app.route('/')
def index():
    msg = Message('主题',sender=os.environ.get('MAIL_USERNAME'),recipients=['431054426@qq.com'])
    msg.body = '文本 body'
    msg.html = '<b>测试flask发送邮件</b>'
    mail.send(msg)

    return '<h1>邮件发送成功</h1>'


if __name__ == '__main__':
    app.run(debug=True)
(venv)zhangkeyuan@opsnotes:~/Test/flask »

####测试: 刷新网页即可发送邮件
(venv)zhangkeyuan@opsnotes:~/Test/flask » python flask-mail.py

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat

####异步邮件发送
(venv)zhangkeyuan@opsnotes:~/Test/flask » cat mail.py

#!/bin/env python
#-*- coding:utf-8 -*-
import os
from flask import Flask, render_template
from flask.ext.mail import Mail,Message
from threading import Thread


app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = '25'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')


mail = Mail(app)

def send_async_email(app,msg):
    with app.app_context():
        mail.send(msg)

@app.route('/')
def index():
    msg = Message('主题',sender=os.environ.get('MAIL_USERNAME'),recipients=['431054426@qq.com'])
    msg.body = '文本 body'
    msg.html = '<b>测试flask发送异步邮件</b>'


    thread = Thread(target=send_async_email,args=[app,msg])
    thread.start()

    return '<h1>邮件发送成功</h1>'


if __name__ == '__main__':
    app.run(debug=True)
(venv)zhangkeyuan@opsnotes:~/Test/flask »

####测试: 刷新网页即可发送邮件
(venv)zhangkeyuan@opsnotes:~/Test/flask » python mail.py

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
OpsNotes wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!