3

I have a project which is structured similar to the overholt and fbone example. I can send emails from all my blueprints fine, but struggle to send outside. E.g. from within a cron script or celery task. I keep getting the error working outside of application context

app/factory.py

from flask import Flask
from .extensions import mail

def create_app(package_name, package_path, settings_override=None,
           register_security_blueprint=True):

    app = Flask(package_name, instance_relative_config=True)

    mail.init_app(app)
    register_blueprints(app, package_name, package_path)
    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app

app/extensions.py

from flask_mail import Mail
mail = Mail()

app/frontend/admin.py

bp = Blueprint('admin', __name__, url_prefix='/admin', static_folder='static')

@bp.route('/')
def admin():
    msg = Message(......)
    mail.send(msg)

Everything up until here works fine. Now I have a separate module in app which has some cron scripts which now fail.

app/cron/alerts.py

from ..extensions import mail
from flask.ext.mail import Message

def alert():
    msg = Message('asdfasdf', sender='hello@example.com', recipients=['hello@example.com'])
    msg.body = 'hello'
    mail.send(msg)

Which produces the error. How can I get around this?

raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context
lennard
  • 523
  • 6
  • 19

2 Answers2

1

You need use Flask-Mail:

from flask_mail import Mail
mail = Mail(app)
JRazor
  • 2,707
  • 18
  • 27
-1

I would recommend going with celery. For the context problem I have found my solution in the following.

Have a look at this:

Miguel Grinberg's Blogpost on celery

Or if you are using the factory pattern in your application:

Celery with Factory Pattern

The second one is some kind of further/extended reading. Both of them helped me a lot. (The second one also solved a context issue for me)

René Jahn
  • 1,155
  • 1
  • 10
  • 27