Send emails with flask and outside context / cronjobs

Viewed 542

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
2 Answers
Related