Search code examples
pythondjangoemaildjango-email

Django email


I am using the Gmail SMTP server to send out emails from users of my website.

These are the default settings in my settings.py

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'pwd'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
SERVER_EMAIL = EMAIL_HOST_USER
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

If I want a user to send an email, I am overriding these settings and sending the email using Django's email sending methods. When an exception occurs in the system, I receive an email from the [email protected]. Sometimes I receive an email from some logged in user. Which could also possibly mean that when a user receives an email sent from my website it has a sent address different from the actual user.

What should be done to avoid this situation?


Solution

  • Django only uses settings.DEFAULT_FROM_EMAIL when any of the mail sending functions pass None or empty string as the sender address. This can be verified in django/core/mail.py.

    When there is an unhandled exception Django calls the mail_admins() function in django/core/mail.py which always uses settings.SERVER_EMAIL and is only sent to addresses listed in settings.ADMINS. This can also be verified in django/core/mail.py.

    The only other place Django itself sends e-mails is if settings.SEND_BROKEN_LINK_EMAILS is True, then CommonMiddleware will send mail to all addresses listed in settings.MANAGERS and the e-mail sender is settings.SERVER_EMAIL.

    Therefore, the only time a regular user will receive e-mail from your site is when you call send_mail(). So, always pass a real address as the from_mail argument and you will avoid users receiving email from settings.SERVER_EMAIL or settings.DEFAULT_FROM_EMAIL.

    Side note: django-registration is at least one example of a Django pluggable that will send mail from settings.DEFAULT_FROM_EMAIL so in cases like this you need to make sure it is a proper e-mail address such as [email protected] or [email protected].