Jun 27, 2019 · Updated: Jan 04, 2021 · by Tim Kamanin
Sending email messages from a web app often seems like throwing stones into a black hole. You create a message, pass it to a mail send function and hope for the best. You don't control an inbox and mail server, so this whole process happens somewhere in between, and you hope it just works.
I think it's time to change that. Email messages can and should be tested like any other piece of a web app. And luckily, Django makes this process super easy.
To send an email message in Django, you can use various email backends: regular SMTP server, GMAIL, or any other service like mailgun or mailchimp.
However, when we run a test, Django's test runner automatically redirects all Django-sent email to a dummy outbox, which lets you test every aspect of sending an email - from the number of messages sent to the contents of each message.
During tests, every outgoing email instead of being sent to the outer world is saved in
django.core.mail.outbox. Thus we get a virtual inbox that we can quickly inspect.
from django.core import mail print(len(mail.outbox))
from django.core import mail first_message = mail.outbox print(first_message.subject) print(first_message.body)
Having these possibilities, you can write tests that verify email contents and delivery.
from django.core import mail def test_send_mail(): # Use Django send_mail function to construct a message # Note that you don't have to use this function at all. # Any other way of sending an email in Django would work just fine. mail.send_mail( 'Example subject here', 'Here is the message body.', 'firstname.lastname@example.org', ['email@example.com'] ) # Now you can test delivery and email contents assert len(mail.outbox) == 1, "Inbox is not empty" assert mail.outbox.subject == 'Subject here' assert mail.outbox.body == 'Here is the message.' assert mail.outbox.from_email == 'firstname.lastname@example.org' assert mail.outbox.to == ['email@example.com']
That's all. I hope you've learned something new. If yes, please share this post as much as you can. Thank you for the support!
Hey, if you've found this useful, please share the post to help other folks find it: