flask-mail的小坑

2018-08-30  本文已影响10人  yytester

<<Flask Web开发:基于Python的Web应用开发实战>>这本书的内容,关于邮件发送的那段代码已经不适用现在的情况了,修改后的极简版代码如下:

#!/usr/bin/python
from flask import Flask,render_template,session,redirect,url_for ,flash 
from flask_mail import Mail,Message
from threading import Thread 

app = Flask(__name__)

app.config['MAIL_SERVER'] = 'smtp.163.com'
app.config['MAIL_PORT'] = 587
#app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'xxx666@163.com' #发件邮箱,邮箱名字和环境变量MAIL_USERNAME保持一致
app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')

mail = Mail(app)

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 

    
def index():
    if app.config['FLASKY_ADMIN']:
            send_email(app.config['FLASKY_ADMIN'], 'New User','mail/new_user', user=user)

代码中三个环境变量配置:

export MAIL_USERNAME= xxx    #发件邮箱名,不需要@xxx.com
export MAIL_PASSWORD=xxxxx  #发件邮箱密码
export FLASKY_ADMIN=qqq666@163.com   #收件邮箱全名,需要加上@xxx.com

不过要记住,程序要发送大量电子邮件时,使用专门发送电子邮件的作业要比给每封邮件都新建一个线程更合适。例如,可以把执行 send_async_email() 函数的操作发给 Celery 任务队列。


注意的地方:

上一篇 下一篇

猜你喜欢

热点阅读