Skip to content

Sending Django Emails [with examples]

Posted in Django

Django Emails makes sending emails – either error messages or user sign up emails via an authentication system – is easy. Let us take a look at the settings you need to have in place in order for emails to be sent from Django successfully.

Let us consider settings for sending emails in Django using Google Mail and Zoho mail, and do well to take note of the differences.

To make use of sending emails, you should have the

configured. If you’re working locally, the ...console.EmailBackend would do, as well as the smtp setting.

Throughout this article, we have the smtp backend setting in place instead.

Gmail Settings

Now this gets you sending all emails from Django, including error messages, sign up emails, and any other custom emails you might wanna send in your application, like a user sending message to another user.

For the latter, it might look like this (this is a snippet from a previous project, Menpha):

The above will send an email from the sender to the list of recipients. This works when using Gmail as the outgoing server.

However, for an outgoing server such as Zoho throws the error, Relaying Disallowed

To fix that, here’s how

Zoho Mail Settings

To fully get all emails sending properly with Zoho Mail when using Django, having these settings in place should get you going without receiving any Relaying Disallowed error messages.

Make sure you setup your Zoho Mail email to have the “Send Mail As” configured. See the 50 seconds video below to learn how:

With the above out of the way, let’s move ahead into our Django to let it speak with the Zoho Mail server.

First, explicitly configure the DEFAULT_FROM_EMAIL setting in Django. In my case, it is noreply@khophi.co, so will be like this:

By default, Django sends emails, administrative ones, using the default email, webmaster@localhost, however, the Zoho mail as seen from the steps in the above video, won’t allow the sender to be webmaster@localhost, and only expects a sender of noreply@khophi.co

Changing the DEFAULT_EMAIL_FROM from the default saves us that.

To therefore actually send an email from our application, like to a user, a slight change needs to happen. This snippet is adapted from packagetome.com

Because we cannot let Zoho Mail send an email without the sender being noreply@khophi.co, we have to make sure the sender is our “Send Mail As” email address.

With the above, a message from the contact form will go from noreply@khophi.co to contact@khophi.co and whatever email is within form.cleaned['sender'].

The form.cleaned['sender'] is there for sender to also get confirmation of email sent.

Conclusion

Sending emails shouldn’t be crazy, and Django makes it a breeze, unlike using a Custom Error View in Django.

I hope you enjoyed this one and see you in the next one.