[Fixed]-Asynchronious email sending in Django

1👍

Problem

From https://github.com/pmclanahan/django-celery-email

By default django-celery-email will use Django’s builtin SMTP email
backend for the actual sending of the mail.

This means you need to run an SMTP server locally to accept the email. That is why you are getting a socket error – cause you don’t have any SMTP server set to receive the email.

Possible Solutions – Local Development

A. Start an SMTP server and use your own client

Option 1

Run a combined SMTP server and client.
Mailcatcher is great for this.

It even comes with django setup instructions!

Set it up then fire it up with:

$ mailcatcher -fv

Note: mailcatcher requires gem (ruby package manager) to install.
So you will have to install that first.
Its probably worth the effort, as mailcatcher works quite nicely and
gives you html and text representations of the email in a browser tab.

For docker users you can get a mailcatcher docker image

Option 2

Run your own SMTP server and a separate mail client.

e.g. Use a simple python SMTP server
From the command line
python -m smtpd -n -c DebuggingServer localhost:1025

in your django settings:


EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = None
EMAIL_HOST_PASSWORD = None
EMAIL_PORT = 1025
EMAIL_USE_TLS = False

Then you will need to setup a client to get those emails.

B. Don’t use SMTP as a backend in your settings

Instead print to the console:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Problem with this is ugly formatting.
HTML will appear as text which makes the email very hard to read. You can output this to a file by manually copying and pasting it into a .html file and opening it in a browser, but that will get boring very fast.

Solution – Continuous Integration Server

Use this for making email accessible to the django test client, so you can check that emails got sent, check the content of email programatically etc.
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

Solution – Production Server

You will need to use a SMTP server again.
Either you can run your own or use Sendgrid, Mailgun, Mandrill or something similar.

Leave a comment