Search code examples
djangoemailassertionsdjango-testing

How can I test alternative body content in EmailMultiAlternatives object using django test system?


I have EmailMultiAlternatives object with text and html content in my view:

email = EmailMultiAlternatives(subject=subject, body=message, from_email=sender, to=recipient)
email.attach_alternative(messageHTML, 'text/html')

When I test the content of message body attribute contains the text version and I don't know how to assert html content:

self.assertHTMLEqual(mail.outbox[0].body, message) # This test passes
self.assertHTMLEqual(mail.outbox[0].<???>, messageHTML) # But here I don't know what to do

Solution

  • When you write - mail.outbox[0], an email object is returned to you which is an instance of EmailMultiAlternatives class. It has an attribute called alternatives which is a list of alternative contents.

    Since you attached only 1 alternative content, you can fetch it like this:

    mail.outbox[0].alternatives[0]
    
    # above will return the following tuple:
    
    ('<html>...</html>', 'text/html')
    
    # \______________/    \_______/
    #        |                |
    #   HTML content        mimetype 
    

    To test the message, you can do this:

    self.assertHTMLEqual(mail.outbox[0].alternatives[0][0], messageHTML)