Testing Email Sending

A snippet showing how to test email sending in Django.


# models.py

from django.db import models

class Newsletter(models.Model):
    subject = models.CharField(max_length=120)
      

# admin.py

from django.contrib import admin
from .models import Newsletter

@admin.register(Newsletter)
class NewsletterAdmin(admin.ModelAdmin):
    list_display = ("subject",)
      

# Result (tests/test_email.py)
from django.test import TestCase
from django.core import mail

class EmailTest(TestCase):
    def test_send_mail(self):
        mail.send_mail("Hello", "Body", "[email protected]", ["[email protected]"])
        self.assertEqual(len(mail.outbox), 1)
        self.assertIn("Hello", mail.outbox[0].subject)
      
Explanation:
  • Django collects sent emails in mail.outbox during tests.
  • Inspect subject, body, recipients, and attachments.
  • Category Testing
  • Total Views 406
  • Last Modified 21 March, 2026
  • Tags #testing #email #mail #unittest
Previous snippet
Testing File Uploads
Next snippet
Testing Admin Views
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.