Sending emails is a necessary function of any modern web application. This page describes how to send emails through transactional email providers using GeniePy.
GeniePy supports sending emails through a few different transactional email service providers (also sometimes referred to as ESPs). This works primarily through setting a few core environment variables followed by setting a few environment variables specific to the service provider you're using.
Configuration
The following two environment variables are required for sending emails, independent of which service provider you're using.
EMAIL_SENDER
: this is the email address used when your application code wants to send an email to your users. Set this to something along the lines of "[email protected]".EMAIL_BACKEND
: this specifies the name of the service provider of your choosing. The following four values are supported:mailgun
,mailjet
,sendgrid
, andnull
.
The null
value for EMAIL_BACKEND
is mostly helpful for local development
where you don't want to send any emails to anyone.
With those two environment variables in place, we can move on to configuring the individual service providers.
Mailjet
Specify valid values for the following three environment variables:
EMAIL_MAILJET_ENDPOINT
: the API endpoint that should be contacted to send emails (this should normally be set tohttps://api.mailjet.com/v3.1/send
)EMAIL_MAILJET_API_KEY
: your API keyEMAIL_MAILJET_API_SECRET
: your API secret
For details on how to obtain these variables, please refer to Mailjet API docs.
Mailgun
Specify valid values for the following two environment variables:
EMAIL_MAILGUN_ENDPOINT
: Mailgun API's base URL which should be contacted to send emailsEMAIL_MAILGUN_API_KEY
: your API key
For details on how to obtain these variables, please refer to Mailgun API reference.
Sendgrid
Specify values for the following two environment variables:
EMAIL_SENDGRID_ENDPOINT
: the API endpoint that should be contacted to send emailsEMAIL_SENDGRID_API_KEY
: your API key provisioned from Sendgrid
For details on how to obtain these variables, please refer to Sendgrid API reference.
Usage
The code around sending emails has been built keeping the facade pattern in mind.
There is an app.services.email
service provided to the application which
defines a send_email
function with the following signature:
async def send_email(
from_: str,
to: str,
subject: str,
html: str,
text: str,
):
...
The job of this function is to check which email service provider is currently
active (based on the EMAIL_BACKEND
setting), initialize the corresponding
provider class, and pass all the data to the instance of that specific backend.
This way your application code does not need to worry about which service provider is currently active. And you can switch service providers overnight if the need be.