Pawel Zadrozny

@pawelzny

About confusing or poorly documented features of tools and libraries I use.


Send emails from Django using Gmail SMTP

26 Jun 2017 development | #python #django #email #smtp

Add this configurations in your settings.py

This configurations is if you work with smtp.gmail.com, other smtp is similiar with configurations.

EMAIL_HOST           = 'smtp.gmail.com'
EMAIL_PORT           = 587
EMAIL_HOST_USER      = '[email protected]'
EMAIL_HOST_PASSWORD  = 'your_password'
EMAIL_USE_TLS        = True
DEFAULT_FROM_EMAIL   = EMAIL_HOST_USER
EMAIL_FROM           = EMAIL_HOST_USER
EMAIL_SUBJECT_PREFIX = '[Project] '
EMAIL_BACKEND        = 'django.core.mail.backends.smtp.EmailBackend'

# MANAGERS
ADMINS = [('Website Admin', '[email protected]')]
MANAGERS = ADMINS + [('Website Manager', '[email protected]')]

Sending email is as easy as creating EmailMessage object and calling send method on it.

from django.conf import settings
from django.core.mail import EmailMessage

subject = 'Internal system message'
body = "This is test email."

EmailMessage(subject=subject, body=body, to=[x[1] for x in settings.MANAGERS]).send()

But what if you want to pretend sending emails?

Change EMAIL_BACKEND setting to console.

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'