Send email from Django with Shipmail
Add Shipmail as a Django email backend. send_mail, EmailMessage and password reset emails then send through the Shipmail API without other changes.
Last updated
Before you start
- A verified sending subdomain, such as
notify.example.com, with an active sender. See Transactional email. - An API key with send access to the sender's mailbox.
- The sender address, such as
hello@notify.example.com. Use the bare address. Shipmail adds the sender name.
Install the SDK
Add the Python SDK and put the key in the environment of your Django process.
pip install shipmailSHIPMAIL_API_KEY=sm_live_...Add the backend
Save it as myapp/email.py. It sends the bare From address, because Shipmail adds the sender name. Each message gets its own idempotency key, so when the SDK retries a 429 or a server error, Shipmail still sends the email once.
# myapp/email.py
import os
import uuid
from email.utils import parseaddr
from django.core.mail.backends.base import BaseEmailBackend
from shipmail import Shipmail, ShipmailError
class ShipmailBackend(BaseEmailBackend):
def __init__(self, fail_silently=False, **kwargs):
super().__init__(fail_silently=fail_silently, **kwargs)
self.client = Shipmail(os.environ["SHIPMAIL_API_KEY"])
def send_messages(self, email_messages):
sent = 0
for message in email_messages:
try:
self.client.messages.send(
self._params(message),
{"idempotency_key": str(uuid.uuid4())},
)
except ShipmailError:
if not self.fail_silently:
raise
else:
sent += 1
return sent
def _params(self, message):
params = {
"from": parseaddr(message.from_email)[1],
"to": message.to,
"subject": message.subject,
}
if message.cc:
params["cc"] = message.cc
if message.bcc:
params["bcc"] = message.bcc
if message.content_subtype == "html":
params["html"] = message.body
else:
params["text"] = message.body
for content, mimetype in getattr(message, "alternatives", []):
if mimetype == "text/html":
params["html"] = content
return paramsMake it the default backend
# settings.py
EMAIL_BACKEND = "myapp.email.ShipmailBackend"
DEFAULT_FROM_EMAIL = "hello@notify.example.com"Existing code sends through Shipmail with no change:
from django.core.mail import send_mail
send_mail(
"Welcome to Acme",
"Thanks for signing up.",
None,
["customer@example.com"],
html_message="<p>Thanks for signing up.</p>",
)Handle errors
If Shipmail refuses the send, send_mail raises a ShipmailError subclass. Pass fail_silently=True to ignore it. If the SDK still gets a 429 after its retries, it raises RateLimitError, and retry_after gives the seconds to wait before you try again. See Rate limits.
Test without sending
Use a sm_test_ key while you build. Shipmail accepts the request, delivers nothing and lists the send under Test in Activity. See Sandbox mode.