0

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('test@gmail.com'):
        user_datastore.create_user(email='test@gmail.com', 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)
jesseCampeez
  • 97
  • 10

3 Answers3

1

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.

cccnrc
  • 1,195
  • 11
  • 27
jwag
  • 662
  • 5
  • 6
1

It's been a while, but you can not send emails while TESTING = True in app.config :)

PicxyB
  • 596
  • 2
  • 8
  • 27
0

In your flask-mail settings file. Define a function for sending mail like this:

def send_email(subject, sender, recipients, text_body, html_body):
   msg = Message(subject, sender=sender, recipients=recipients)
   msg.body = text_body
   msg.html = html_body
   mail.send(msg)

Call this method where ever you want to trigger a mail action. For example:

@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('test@gmail.com'):
     user_datastore.create_user(email='test@gmail.com', 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()
     send_mail(subject="AccountCreation",Sender="somesender",recepient="somerecepient",text_body="congratulations account created ",text_html=None)
   db.session.commit()
  • ok I believe this will work, but I was looking more to use the built in method that comes with flask-security to avoid problems later with functions such as reset password etc – jesseCampeez Jun 03 '19 at 18:12
  • Refer to [this](https://www.google.com/url?sa=t&source=web&rct=j&url=https://realpython.com/handling-email-confirmation-in-flask/&ved=2ahUKEwivmIP19c3iAhXh73MBHcpmD4sQFjAAegQIAxAB&usg=AOvVaw3wGlqf1jK_Viz6Xi2R-6fK&cshid=1559585828638) and [this](https://www.google.com/url?sa=t&source=web&rct=j&url=https://readthedocs.org/projects/flask-security/downloads/pdf/latest/&ved=2ahUKEwiKieyV983iAhU17HMBHdKSDmwQFjABegQIAxAB&usg=AOvVaw3v1a7cjehRjlE5ON2Ndwzb) – Tech at The Sparks Foundation Jun 03 '19 at 18:21
  • I have been through both multiple times. I still do not understand how to get the intended functions of flask-security to work. – jesseCampeez Jun 04 '19 at 01:29