Skip to content

How to send email from Django

This how-to guide covers how to send email from a Django application hosted in the Cloud using the User Notify service. If you are writing your application in Python but not using Django you should follow a different guide.

Prerequisites

You must have first registered your service. You should have a "service id" as part of that step. In this guide we shall use punt-booker as an example service id.

Your application must be running as a cloud workload with a service account identity registered with the User Notify service or, if running on your local machine, you must be authenticated via gcloud auth application-default login with an account which can impersonate such a service account.

Configuring Django

If you are using our standard boilerplate, you will be using poetry to manage dependencies. If not already present, add a uis-devops source for packages:

poetry source add --priority=explicit uis-devops \
    https://gitlab.developers.cam.ac.uk/api/v4/groups/5/-/packages/pypi/simple

Then add the ucam-user-notify library as a dependency:

poetry add --source=uis-devops ucam-user-notify

Add the following to your Django settings:

# Use the User Notify email backend.
EMAIL_BACKEND = "ucam_user_notify.django.UserNotifyEmailBackend"

# The service id as registered with the User Notify service.
USER_NOTIFY_SERVICE_ID = "punt-booker"

# We set the default "From" email to None so that the From address registered in
# the User Notify service is used. You can customise it if you want but the From
# address must match one of those registered with the service.
DEFAULT_FROM_EMAIL = None

Emails sent using Django's send_email function should now go through the User Notify service.

Next steps