From 94e1dbe09bf77254ae91f9bfec2ad9ffd1dd607d Mon Sep 17 00:00:00 2001 From: tmeissner Date: Sun, 21 Oct 2018 00:01:25 +0200 Subject: [PATCH] Chapter 6: Email support with Flask-Mail (6a) --- hello.py | 21 +++++++++++++++++++++ templates/mail/new_user.html | 1 + templates/mail/new_user.txt | 1 + 3 files changed, 23 insertions(+) create mode 100644 templates/mail/new_user.html create mode 100644 templates/mail/new_user.txt diff --git a/hello.py b/hello.py index 693fcfa..ba94a04 100644 --- a/hello.py +++ b/hello.py @@ -7,6 +7,7 @@ from wtforms import StringField, SubmitField from wtforms.validators import DataRequired from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from flask_mail import Mail, Message basedir = os.path.abspath(os.path.dirname(__file__)) @@ -16,11 +17,20 @@ app.config['SECRET_KEY'] = 'hard to guess string' app.config['SQLALCHEMY_DATABASE_URI'] = \ 'sqlite:///' + os.path.join(basedir, 'data.sqlite') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False +app.config['MAIL_SERVER'] = 'smtp.strato.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') +app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]' +app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin ' +app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN') bootstrap = Bootstrap(app) moment = Moment(app) db = SQLAlchemy(app) migrate = Migrate(app, db) +mail = Mail(app) class Role(db.Model): @@ -43,6 +53,14 @@ class User(db.Model): return '' % self.username +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) + + class NameForm(FlaskForm): name = StringField('What is your name?', validators=[DataRequired()]) submit = SubmitField('Submit') @@ -73,6 +91,9 @@ def index(): db.session.add(user) db.session.commit() session['known'] = False + if app.config['FLASKY_ADMIN']: + send_email(app.config['FLASKY_ADMIN'], ' New user', + 'mail/new_user', user=user) else: session['known'] = True session['name'] = form.name.data diff --git a/templates/mail/new_user.html b/templates/mail/new_user.html new file mode 100644 index 0000000..7726779 --- /dev/null +++ b/templates/mail/new_user.html @@ -0,0 +1 @@ +User {{ user.username }} has joined. \ No newline at end of file diff --git a/templates/mail/new_user.txt b/templates/mail/new_user.txt new file mode 100644 index 0000000..8e444f3 --- /dev/null +++ b/templates/mail/new_user.txt @@ -0,0 +1 @@ +User {{ user.username }} has joined. \ No newline at end of file