title: Flask-Mail - Sending email asynchronously, based on Flask-Cookiecutter
body: <p>My flask project is based on <a href="https://github.com/sloria/cookiecutter-flask" rel="nofollow noreferrer">Flask-Cookiecutter</a> and I need to send emails asynchronously.</p>
  
  <p>Function for sending email was configured by <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi-email-support" rel="nofollow noreferrer">Miguel’s Tutorial</a> and sending synchronously works fine, but i don’t know, how I can modify it for sending asynchronously.</p>
  
  <p>My app.py</p>
  
  <pre><code>def create_app(config_object=ProdConfig):
      app = Flask(__name__)
      app.config.from_object(config_object)
      register_extensions(app)
      register_blueprints(app)
      register_errorhandlers(app)
      return app
  
  def register_extensions(app):
      assets.init_app(app)
      bcrypt.init_app(app)
      cache.init_app(app)
      db.init_app(app)
      login_manager.init_app(app)
      debug_toolbar.init_app(app)
      migrate.init_app(app, db)
      mail.init_app(app)
      return None
  </code></pre>
  
  <p>my view.py</p>
  
  <pre><code>from flask import current_app
  
  @async
  def send_async_email(current_app, msg):
      with current_app.app_context():
          print('##### spustam async')
          mail.send(msg)
  
  
  # Function for sending emails
  def send_email(to, subject, template, **kwargs):
      msg = Message(subject, recipients=[to])
      msg.html = render_template('emails/' + template, **kwargs)
      send_async_email(current_app, msg)
  </code></pre>
  
  <p>route in view.py</p>
  
  <pre><code>@blueprint.route('/mailer', methods=['GET', 'POST'])
  def mailer():
      user = current_user.full_name
      send_email(('name@gmail.com'),
                 'New mail', 'test.html',
                 user=user)
      return "Mail has been send."
  </code></pre>
  
  <p><strong>Application run in my localhost and it's starting with command:</strong></p>
  
  <pre><code>python manage.py server
  </code></pre>
  
  <p>When i call function for sending mail, output in console is:</p>
  
  <pre><code>RuntimeError: Working outside of application context.
  
  This typically means that you attempted to use functionality that needed
  to interface with the current application object in a way.  To solve
  this set up an application context with app.app_context().  See the
  documentation for more information.
  </code></pre>
  
  <p>Thanks for any answer.</p>