Python – How to test the content of Django emails?

How to test the content of Django emails?… here is a solution to the problem.

How to test the content of Django emails?

I’m new to Django and I’m trying to check if there’s some text in the outbound email using unittest:

class test_send_daily_email(TestCase):
    def test_success(self):
        self.assertIn(mail.outbox[0].body, "My email's contents")

However, I’m having problems with mail.outbox[0].body. It will output \nMy email's contents\n and will not match the test text.

I tried several different fixes but none of them worked :

  • str(mail.outbox[0].body).rstrip() – Returns an identical string
  • str(mail.outbox[0].body).decode('utf-8') – attribute-free decoding

Sorry, I know this must be a trivial task. In Rails, I use something like Nokogiri to parse text. What is the correct way to parse this in Django? I can’t find instructions for this in the documentation


This depends on the actual content of your message (plain text or HTML), but the easy way to do this is to also encode the string you want to test.

# if you are testing HTML content
self.assertTextInHTML("My email's contents", mail.outbox[0].body)

# the string may need escaping the same way django escapes
from django.utils.html import escape
self.assertIn(escape("My email's contents"), mail.outbox[0].body)

Related Problems and Solutions