Skip to content

Instantly share code, notes, and snippets.

@phpdude
Last active April 6, 2023 05:05
Show Gist options
  • Save phpdude/34fc7001e0b04ecf7fb18516b0577287 to your computer and use it in GitHub Desktop.
Save phpdude/34fc7001e0b04ecf7fb18516b0577287 to your computer and use it in GitHub Desktop.

Simplest Async Email Backend for Django

What is this?

It is simplest email backend for Django which supports async email delivery in parallel threads. Keep it simple! It has various analogs, you can google for it yourself.

Requirements

Django async email backend requires futures library. So you need to install it with pip install futures.

Django configuration settings

This is simple backend so you need to configure django to use our backend and you can alter pool size with EMAIL_BACKEND_POOL_SIZE.

EMAIL_BACKEND = 'utils.email.EmailBackend'
EMAIL_BACKEND_POOL_SIZE = 15 # default value
from concurrent import futures
from django.conf import settings
from django.core.mail.backends.smtp import EmailBackend as BaseEmailBackend
class EmailBackend(BaseEmailBackend):
"""
A wrapper that manages the SMTP network connection asynchronously
"""
def __init__(self, *args, **kwargs):
super(EmailBackend, self).__init__(*args, **kwargs)
self.executor = futures.ThreadPoolExecutor(
max_workers=int(getattr(settings, 'EMAIL_BACKEND_POOL_SIZE', 15))
)
def send_messages(self, email_messages):
return self.executor.submit(super(EmailBackend, self).send_messages, email_messages)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment