Skip to content

How to send email from Python code

This how-to guide covers how to send email from Python code hosted in the Cloud using the User Notify service. If you are writing your application in 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 Python code 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.

Sending email

Install the ucam-user-notify library as covered in its getting started documentation.

In your code, create a Session object. This object performs some one-time setup and so you can persist the session instance between incoming requests for greater performance.

from ucam_user_notify import Session

session = Session.for_service("punt-booking")

When you actually want to send email, use the send_mail method of the Session object.

from ucam_user_notify import EmailMessage

session.send_email(
    EmailMessage(
        to_addresses=["success@simulator.amazonses.com"],
        subject="testing",
        body_text="This is a test.",
    )
)

Next steps