django: using threading to speed up send_mail
django.core.mail.send_mail provides a very convenient abstraction to send an email to multiple recipients. But calling send_mail is a blocking call. This means that if you want to send an email in response to a user action, the server will not respond till the email is sent. This problem is magnified when you have to send multiple emails for a user action. Imagine sending emails to 10-15 people in a thread to notify of a new comment.
I decided to change the send_mail function to non-blocking call. The result is the following code,
from django.core.mail import send_mail as django_send_mail import threading from datetime import datetime as dt def send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None): class Sender(threading.Thread): def run(self): django_send_mail(subject, message, from_email, recipient_list, fail_silently, auth_user, auth_password) s=Sender() s.start() return True
The code has a function send_mail which serves as a wrapper on the django.core.mail.send_mail function. When called, the function simply creates a thread and returns so the response for user is instantaneous. The thread then calls the django.core.mail.send_mail (imported as django_send_mail).
Related posts:

Recent Comments