Search code examples
pythonflaskflask-security

Email not sending on create_user


I am trying to use flask-security and have become helplessly stuck trying to send an email when create_user is called. The user is being created. The roles are working, however, I can not find any documentation explaining how to send an email to the user when they sign up.

To keep things simple I am just using the code from the doc's to create a user before first request.

# Create a user to test with

@app.before_first_request
def create_user():
    db.create_all()

# Create the Roles "admin" and "office_owner" -- unless they already exist
    user_datastore.find_or_create_role(name='admin', description='Administrator')
    user_datastore.find_or_create_role(name='office_owner', description='Office owner')

    if not user_datastore.get_user('[email protected]'):
        user_datastore.create_user(email='[email protected]', password=flask_security.utils.hash_password('password'))

    # Commit any database changes; the User and Roles must exist before we can add a Role to the User
        db.session.commit()



    db.session.commit()

Here is my flask-mail settings

from flask import Flask
from flask_mail import Mail, Message
import os

mail_keys = {
  'password_key': os.environ['EMAIL_PASSWORD'],
  }

app =Flask(__name__)
mail=Mail(app)



app.config['MAIL_SERVER']='smtp.sendgrid.net'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'apikey'
app.config['MAIL_PASSWORD'] = mail_keys['password_key']
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail=Mail(app)

config.py is

import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):


SQLALCHEMY_DATABASE_URI='postgresql://postgres///'

SQLALCHEMY_TRACK_MODIFICATIONS = False

SECURITY_PASSWORD_SALT = 'hjdsafjkhalkj'
SECURITY_PASSWORD_HASH='bcrypt'
SECURITY_CONFIRMABLE=True
SECURITY_REGISTERABLE=True
SECURITY_RECOVERABLE=True
SECURITY_CHANGEABLE=True

settings.py

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import Config
from flask_mail import Mail, Message
from flask_migrate import Migrate

app=Flask(__name__)
app.config.from_object(Config)

mail=Mail(app)
db=SQLAlchemy(app)
migrate = Migrate(app, db)

Solution

  • The simplest answer is the create_user is an admin function. Flask-Security doesn't know anything about this since it isn't associated with a view.

    Out of the box - as documented in the configuration.rst it can send mail for: SEND_REGISTER_EMAIL, SEND_PASSWORD_CHANGE_EMAIL, SEND_PASSWORD_RESET_EMAIL, SEND_PASSWORD_RESET_NOTICE_EMAIL

    that is all that is built in. Most sites would enable SECURITY_REGISTERABLE and allow users to sign up - at which point they will get an email.