Browse Source

Chapter 6: Email support with Flask-Mail (6a)

master
T. Meissner 6 years ago
parent
commit
94e1dbe09b
3 changed files with 23 additions and 0 deletions
  1. +21
    -0
      hello.py
  2. +1
    -0
      templates/mail/new_user.html
  3. +1
    -0
      templates/mail/new_user.txt

+ 21
- 0
hello.py View File

@ -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 <flasky@example.com>'
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 '<User %r>' % 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


+ 1
- 0
templates/mail/new_user.html View File

@ -0,0 +1 @@
User <b>{{ user.username }}</b> has joined.

+ 1
- 0
templates/mail/new_user.txt View File

@ -0,0 +1 @@
User {{ user.username }} has joined.

Loading…
Cancel
Save