Skip to content

Instantly share code, notes, and snippets.

@scotu
Forked from seanmckaybeck/mailgun.py
Last active July 26, 2016 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scotu/98ef5cceb03d76abac74ec389b7d87f4 to your computer and use it in GitHub Desktop.
Save scotu/98ef5cceb03d76abac74ec389b7d87f4 to your computer and use it in GitHub Desktop.
No-external-dependency email sending function through Mailgun's REST api for python
# -*- coding: utf-8 -*-
"""
Copyright 2016 Sean Beck, Matteo Scotuzzi
MIT license
A simple script that provides a function to send an email via Mailgun with no
external dependencies.
This requires obtaining an API key from Mailgun. Make also sure to setup the defaults in the
MAILGUN_API_KEY, DEFAULT_EMAIL_SENDING_DOMAIN, DEFAULT_EMAIL_SENDING_ADDRESS constants after
the imports.
Mailgun will generate a sending domain for you, so just use that if you do not have your own domain.
"""
try:
# For Python 3.0 and later
from urllib.request import urlopen, Request
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen, Request
import urllib
import base64
MAILGUN_API_KEY = 'key-xxx'
DEFAULT_EMAIL_SENDING_DOMAIN = 'example.com'
DEFAULT_EMAIL_SENDING_ADDRESS = 'info@example.com'
def mailgun_notify(**kwargs):
"""
:param kwargs: Pass in a dictionary like so containing your args - mailgun_notify(**d)
:return: None
param api_key: Your Mailgun API key
param domain: The domain associated with your Mailgun account
param from: A string representing the sending email address. This usually
looks something like "Mailgun <mailgun@mydomain.com>"
param to: A list of strings representing email addresses of your intended
recipients (cc and bcc require the same kind of data in input)
param subject: A string to be used as your email's subject
param text: A string representing the body of your email in text.
Those are basic parameters to the Mailgun API. This function requires you specify "to" and
"subject" parameters while others are optional (as long as you set the default constants above:
MAILGUN_API_KEY, DEFAULT_EMAIL_SENDING_DOMAIN, DEFAULT_EMAIL_SENDING_ADDRESS).
All other possible parameters that can be sent via the API can be found here:
https://documentation.mailgun.com/api-sending.html#sending.
If you want an HTML email instead of a text-based email, use the "html" parameter instead of "text"
"""
params = ['to', 'subject']
if any(param not in kwargs for param in params):
raise Exception('Please specify all params: {}'.format(params))
kwargs['api_key'] = kwargs.pop('api_key', MAILGUN_API_KEY)
kwargs['domain'] = kwargs.pop('domain', DEFAULT_EMAIL_SENDING_DOMAIN)
kwargs['from'] = kwargs.pop('from', DEFAULT_EMAIL_SENDING_ADDRESS)
kwargs['to'] = ','.join(kwargs['to'])
if 'bcc' in kwargs:
kwargs['bcc'] = ','.join(kwargs['bcc'])
if 'cc' in kwargs:
kwargs['cc'] = ','.join(kwargs['cc'])
data = {param: kwargs[param] for param in kwargs if param not in ['api_key', 'domain']}
url = 'https://api.mailgun.net/v3/{}/messages'.format(kwargs['domain'])
data = urllib.urlencode(data)
req = Request(url, data)
base64string = base64.encodestring('%s:%s' % ('api', kwargs['api_key'])).replace(
'\n', '')
req.add_header("Authorization", "Basic %s" % base64string)
response = urlopen(req)
if response.getcode() != 200:
raise Exception('Request was not successful. Status code: {}'.format(req.status_code))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment