SMTP

Django (SMTP)

Send email from Django through MailBlastr using the built-in SMTP email backend.

Django ships with an SMTP email backend, so you can send through MailBlastr without any extra dependencies. Configure the backend with the MailBlastr relay and authenticate with your API key. SMTP sends appear in your dashboard and event log just like API sends.

Prerequisites

1. Set your API key

Export your API key as an environment variable so it never lives in source.

export MAILBLASTR_API_KEY="mb_xxxxxxxxx"

2. Configure the SMTP backend

Set the SMTP attributes in your settings.py file.

settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
MAILBLASTR_SMTP_PORT = 587
MAILBLASTR_SMTP_USERNAME = 'mailblastr'
MAILBLASTR_SMTP_HOST = 'smtp.mailblastr.com'

3. Send email using EmailMessage

Use Django's get_connection and EmailMessage, reading the API key from the environment. The from_email must be on a verified domain.

import os
from django.conf import settings
from django.http import JsonResponse
from django.core.mail import EmailMessage, get_connection

# Sample Django view
def index(request):

    subject = "Hello from Django SMTP"
    recipient_list = ["delivered@example.com"]
    from_email = "onboarding@yourdomain.com"
    message = "<strong>it works!</strong>"

    with get_connection(
        host=settings.MAILBLASTR_SMTP_HOST,
        port=settings.MAILBLASTR_SMTP_PORT,
        username=settings.MAILBLASTR_SMTP_USERNAME,
        password=os.environ["MAILBLASTR_API_KEY"],
        use_tls=True,
        ) as connection:
            r = EmailMessage(
                  subject=subject,
                  body=message,
                  to=recipient_list,
                  from_email=from_email,
                  connection=connection).send()
    return JsonResponse({"status": "ok"})
Port 587 with use_tls=True uses STARTTLS. For implicit TLS, use port 465 with use_ssl=True instead. See Send an email for the HTTP API.