Sending Django Emails [with examples]
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
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
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
# Example for using Gmail EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword'
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):
@login_required def notify_email(request, slug): """ Send notification email to original owner of device who lost it """ grab = Item.objects.get(slug=slug) if request.method == "POST": form = NotifyEmailForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = request.user.email recipients = [grab.created_by.email] recipients.append(sender) send_mail(subject, message, sender, recipients) return HttpResponseRedirect('/notify/thanks') # Redirect after POST else: form = NotifyEmailForm() # An unbound form return render(request, 'send-mail.html', {'form': form, 'object': slug, })
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:
DEFAULT_FROM_EMAIL = 'noreply@khophi.co' SERVER_MAIL = 'noreply@khophi.co' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Example for using Zoho Mail as email sending backend EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.zoho.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'noreply@khophi.co' EMAIL_HOST_PASSWORD = 'mypassword'
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
def contact(request): """Send Contact Email""" if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] send_mail_from = 'noreply@khophi.co' # this sender refers to person who the email is from # as indicated in the contact form recipients = ['contact@khophi.co', form.cleaned_data['sender']] send_mail(subject, message, sender, recipients) return HttpResponseRedirect('/help/contact?sent=yes') # Redirect after POST else: form = ContactForm() # An unbound form return render(request, 'contact.html', {'form': form, 'sent': request.GET.get('sent', '') })
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.