Python Flask with celery out of application context


I am building a website using python Flask. Everything is going good and now I am trying to implement celery.

That was going good as well until I tried to send an email using flask-mail from celery. Now I am getting an "working outside of application context" error.

full traceback is

  Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/celery/task/", line 228, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/celery/task/", line 415, in __protected_call__
    return*args, **kwargs)
  File "/home/ryan/www/CG-Website/src/util/", line 28, in send_forgot_email
    msg = Message("Recover your Crusade Gaming Account")
  File "/usr/lib/python2.7/site-packages/", line 178, in __init__
    sender = current_app.config.get("DEFAULT_MAIL_SENDER")
  File "/usr/lib/python2.7/site-packages/werkzeug/", line 336, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/usr/lib/python2.7/site-packages/werkzeug/", line 295, in _get_current_object
    return self.__local()
  File "/usr/lib/python2.7/site-packages/flask/", line 26, in _find_app
    raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context

This is my mail function:

def send_forgot_email(email, ref):
    global mail
    msg = Message("Recover your Crusade Gaming Account")
    msg.recipients = [email]
    msg.sender = "Crusade Gaming"
    msg.html = \
        Hello Person,<br/>

        You have requested your password be reset. <a href="{0}" >Click here recover your account</a> or copy and paste this link in to your browser: {0} <br />

        If you did not request that your password be reset, please ignore this.
        """.format(url_for('account.forgot', ref=ref, _external=True))

This is my celery file:

from __future__ import absolute_import

from celery import Celery

celery = Celery('src.tasks',

if __name__ == "__main__":
4/25/2013 5:49:28 PM

Flask-mail needs the Flask application context to work correctly. Instantiate the app object on the celery side and use app.app_context like this:

with app.app_context():
4/25/2013 6:10:59 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow