Django SendGrid v5 Backend

1.3.1 · active · verified Wed Apr 15

An implementation of Django's EmailBackend compatible with sendgrid-python v5+. It allows Django applications to send emails via SendGrid's API, leveraging SendGrid's full feature set including personalizations, attachments, and tracking. The current version is 1.3.1, and it typically releases updates every few months.

Warnings

Install

Imports

Quickstart

Configure `EMAIL_BACKEND` and `SENDGRID_API_KEY` in your Django `settings.py`. Then use Django's standard `send_mail` or `EmailMessage` functions to send emails. Ensure `SENDGRID_API_KEY` is set as an environment variable or directly in settings. `SENDGRID_SANDBOX_MODE = True` can be used for testing without consuming SendGrid credits.

import os
from django.core.mail import send_mail, EmailMessage
from django.conf import settings

# --- Minimal Django settings configuration for demonstration ---
# In a real Django project, these would be in your settings.py
# and Django's settings would already be configured.
if not settings.configured:
    settings.configure(
        EMAIL_BACKEND='sendgrid_backend.SendgridBackend',
        SENDGRID_API_KEY=os.environ.get('SENDGRID_API_KEY', 'DUMMY_SENDGRID_API_KEY'),
        # Optional: Set sandbox mode for testing without sending real emails
        # SENDGRID_SANDBOX_MODE=True,
        DEBUG=True # Required for settings.configure
    )

print(f"Using SendGrid API Key: {settings.SENDGRID_API_KEY[:5]}... (first 5 chars)")

# --- Sending a basic email ---
try:
    send_mail(
        'Hello from Django SendGrid!',
        'This is a test email sent via SendGrid.',
        'from@example.com', # Must be a verified sender in SendGrid
        ['to@example.com'],
        fail_silently=False,
    )
    print("Basic email sent successfully (or attempted if in sandbox).")
except Exception as e:
    print(f"Error sending basic email: {e}")

# --- Sending an email with more options using EmailMessage ---
try:
    email = EmailMessage(
        'Advanced Django SendGrid Email',
        'This email uses EmailMessage for more control.',
        'from@example.com',
        ['to@example.com'],
        reply_to=['reply@example.com'],
        headers={'X-Custom-Header': 'My-Value'},
    )
    # Example of adding a personalization (requires sendgrid.Personalization object or dict)
    # from sendgrid.helpers.mail import Personalization, Email
    # p = Personalization()
    # p.add_to(Email('another_recipient@example.com'))
    # email.personalizations = [p]

    # Example of using a SendGrid Dynamic Template
    # email.template_id = 'd-xxxxxxxxxxxxxxxxxxxxxxx'
    # email.dynamic_template_data = {'name': 'User', 'message': 'Welcome!'}

    email.send(fail_silently=False)
    print("Advanced email sent successfully (or attempted if in sandbox).")
except Exception as e:
    print(f"Error sending advanced email: {e}")

view raw JSON →