Sending email from your Django application with Mailgun

 

Email is an essential part of any web application, from activating users to sending notifications and updates, it’s role cannot be underestimated.

You want your email delivered on time and not marked as spam , with Mailgun you can send upto 10,000 emails a month for free .
By the end of this post you should be able to have you Django application delivering your emails through mailgun.

Prerequisites

 Before we get started with the installation you will need to setup your mailgun account and get api keys, there is a quick start guide  , once you’ve signed up and have your API keys, I strongly suggest you go ahead and verify your domain to remove the 300 email limit and the `sent via mailgun.org` message from your emails.

Installation

Now that you have created your account and have your mailgun API keys we can get started configuring your Django application to start sending email. django-mailgun is an email backend for Django that should have everything you need to get started, the best way to install it is via pip

pip install django-mailgun

Once you are done installing django-mailgun you will need to tweak your settings.py file

EMAIL_BACKEND = 'django_mailgun.MailgunBackend'
MAILGUN_ACCESS_KEY = 'ACCESS-KEY'
MAILGUN_SERVER_NAME = 'SERVER-NAME'

Replace ACCESS-KEY  with your mailgun api-key and SERVER-NAME with your mailgun api-base url , you will find all those details on your dashboard.

django.core.mail.send_mail is now configured to use the django-mailgun as its email backend, all your email messages will be routed through mailgun.
from django.core.mail import EmailMultiAlternatives

def awesome_view():
    '''send email via mailgun'''
    subject = "Hello, its me"
    text_content = "I was wondering if after all these years"
    sender = "alone@fromtheotherside.com"
    receipient = "movedon@fromtheotherside.com"
    msg = EmailMultiAlternatives(subject, text_content, sender, [receipient])
    respone = msg.send()
    # do something with response

You should note that django-mailgun does not validate your email message data for compliance with Mailgun’s API , you will have to make sure you follow mailgun email best practises

Madra David
Madra David
1 minute read
TL;DR

Share this article

Next Post

Securing your django application with letsencrypt and django-sslify

Previous Post

Adding SMS messaging to your Django application with Twilio

I send out tips on how to improve your website's performance

Find new customers and prospects in less than 30 seconds.
Build outbound email prospecting lists in seconds.

I send out tips on how to improve your website's performance

user-image

Published mars 23 2016

by Madra David