Integrations

Django SMTP

Send emails in Django using our SMTP relay
Developer
Price

Free up to 3,000 emails/month

Last Updated

24/08/2023

Integration Support

Contact us via the chat beacon or our support email.

Prerequisites

To get the most out of this guide, you’ll need to:

1. Setup your environment

Create and activate your new virtualenv:

virtualenv venv
source venv/bin/activate

Install dependencies:

pip install -r requirements.txt

Set your MAILERSEND_API_KEY environment variable by running:

export MAILERSEND_API_KEY="XXX"

where XXX is your API token.

2. Send email using Django’s SMTP EmailMessage

Set the necessary attributes in your settings.py file:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
MAILERSEND_SMTP_PORT = 587
MAILERSEND_SMTP_USERNAME = 'XXXX@verified-domain.com'
MAILERSEND_SMTP_HOST = 'smtp.mailersend.net'

Use Django’s get_connection and EmailMessage:

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 {$company}!"
    recipient_list = ["john@mailersend.com"]
    from_email = "hello@mailersend.com"
    message = "<strong>This is just a friendly hello from your friends at {$company}.</strong>"

    with get_connection(
        host=settings.MAILERSEND_SMTP_HOST,
        port=settings.MAILERSEND_SMTP_PORT,
        username=settings.MAILERSEND_SMTP_USERNAME,
        password=os.environ["MAILERSEND_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"})