Skip to content
This repository has been archived by the owner on Feb 22, 2024. It is now read-only.

Asynchronous mail sending #325

Closed
jvsteiner opened this issue Oct 7, 2014 · 5 comments
Closed

Asynchronous mail sending #325

jvsteiner opened this issue Oct 7, 2014 · 5 comments

Comments

@jvsteiner
Copy link

It might be nice to be able to configure the default mails that are sent out for email authentication to be able to be sent asynchronously, so the thread is not blocked when signups occur.

@jvsteiner
Copy link
Author

I was able to do this myself, as follows:

decorator.py:

from threading import Thread

def async(f):
    def wrapper(*args, **kwargs):
        thr = Thread(target=f, args=args, kwargs=kwargs)
        thr.start()
    return wrapper

and in app.py:

from decorators import async
security = Security(app, user_datastore)

@async
def send_security_email(msg):
    with app.app_context():
       mail.send(msg)

@security.send_mail_task
def async_security_email(msg):
    send_security_email(msg)

Hope this helps someone looking to do the same.

@DukeLeto
Copy link

DukeLeto commented Oct 8, 2014

Excellent. Thanks! I actually took a stab at incorporating this yesterday but ran out of time and was having circular import issues. The way you've applied seems to address that. Where did you find @security.send_mail_task declared btw?

@jvsteiner
Copy link
Author

I found it referenced here: https://pythonhosted.org/Flask-Security/customizing.html#emails-with-celery and decided to try the pattern mentioned in Miguel Grinberg's blog: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi-email-support

@joshgeller
Copy link

Any tips on getting this set up with an application factory function? I'm running into issues with circular imports. Not sure exactly where to drop the decorators. Thanks in advance.

@jvsteiner
Copy link
Author

not sure about application factory functions, but I put it in the decorator.py file like shown above. that file doesn't import anything but Thread, which is probably why I didn't get circular imports. I created it for this purpose, though now it has some other odds and ends in it. it's just one more file, and worked great for me.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

4 participants