Browse Source

Chapter 6: Asynchronous emails (6b)

master
T. Meissner 6 years ago
parent
commit
88514c1e70
1 changed files with 9 additions and 1 deletions
  1. +9
    -1
      hello.py

+ 9
- 1
hello.py View File

@ -1,4 +1,5 @@
import os import os
from threading import Thread
from flask import Flask, render_template, session, redirect, url_for from flask import Flask, render_template, session, redirect, url_for
from flask_bootstrap import Bootstrap from flask_bootstrap import Bootstrap
from flask_moment import Moment from flask_moment import Moment
@ -53,12 +54,19 @@ class User(db.Model):
return '<User %r>' % self.username return '<User %r>' % self.username
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(to, subject, template, **kwargs): def send_email(to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject, msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to]) sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs) msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs) msg.html = render_template(template + '.html', **kwargs)
mail.send(msg)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
class NameForm(FlaskForm): class NameForm(FlaskForm):


Loading…
Cancel
Save