2
from flask import current_app as app
from flask import render_template
from threading import Thread
from flask_mail import Message



def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['MAIL_SENDER'], recipients=[to])
    # msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=send_async_email, args=(app,msg))
    thr.start()
    return thr
    #mail.send(msg)

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 some way. To solve this, set up an application context with app.app_context(). See the documentation for more information.

I thought I have created the app_context, yet the code still displays runtime error. Please help, Thanks.

Ahmad Khidir
  • 140
  • 1
  • 9

2 Answers2

5

You would call the async_send_mail function with something like this:

   app = current_app._get_current_object()
   thr = Thread(target=async_send_mail, args=[app, msg])
   thr.start()

And then the async function would look like this:

def async_send_mail(app, msg):
   with app.app_context():
      mail.send(msg)
Ron Bertino
  • 141
  • 1
  • 7
0
app = current_app._get_current_object()
with app.app_context():
    pass
    # send email here

or

from main import app
with app.app_context():
    pass

# main.py
app = Flask(__name__)

_get_current_object():

Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context.

current_app is a Flask proxy object:

current_app = LocalProxy(_find_app)

You can only get app object from current_app in current thread

joshua
  • 325
  • 1
  • 8
  • still showing the error, also main is a blueprint and app is not importing from it ```ImportError: cannot import name 'app' from 'app.main' (C:\Users\USER\Documents\Global\voting2\app\main\__init__.py)``` – Ahmad Khidir Sep 19 '20 at 10:57