• Sept. 7, 2022

How to debug email rendering in Django

Every web application sends emails. While Django has a very sophisticated emailing system that makes a lot of things easier, you as the programmer still have to code the HTML template and send the correct data to be rendered to the template. Of course, you have to test everything before deploying it to production, because especially in the case of emails, HTML can be quite problematic. Each email client renders HTML in its own way, inline CSS styles must be used in the email, JavaScript doesn't work, all links must have absolute addresses, and other differences from rendering a traditional web page.

In the case of sending emails, you run into the problem that you don't run the SMTP server needed to send the email on the localhost. Anyone can think of sending emails through their regular email account to test what they need. This solution is quite inappropriate for several reasons:

  1. Some email providers (Google) require a higher level of communication security and will not allow you to use the classic SMTP AUTH authentication.
  2. If you send "bad" emails, they may not arrive at all as a result, because they will be blocked by Antispam filters and other mechanisms.
  3. It will suck to test generating emails for different users because you will have to have a different email address for each user.

For email testing on localhost use filebased EMAIL BACKEND.

  1. Set Filebased EMAIL_BACKEND in your project settings and let the emails generate to a folder within the project.
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = os.path.join(BASE_DIR, "temp", "emails")

2. Send an email.

from django.core.mail import send_mail

    'Subject here',
    'Here is the message.',

3. Go to the folder where the emails are generated.

cd BASE_DIR/temp/emails/

4. Change the extensions of the generated file

mv 2022090410344444.log 2022090410344444.eml

5. Open the file using an email client such as Thunderbird or Evolution

Now you have exactly the same view of the email as if you had sent it via SMTP.

Zajímá Vás víc?

Neváhejte nás kontaktovat.