Sending Email with Mailgun

The Mailgun API is built on HTTP and is RESTful. It uses predictable, resource-oriented URLs and built-in HTTP capabilities for passing parameters and authentication. The Mailgun API responds with standard HTTP response codes to indicate errors, and returns JSON.

Mailgun has published libraries for various languages. You can use these libraries or your favorite HTTP/REST library to make HTTP calls to Mailgun.

For more code samples in other programming languages, see Mailgun's documentation.

Pricing

As a Google Cloud Platform user, your first 30,000 messages are free every month. See the monthly pricing calculator on the sign up page for pricing on additional messages and volume discounts.

Setup

Sending a plain text email

def send_simple_message(recipient):
    http = httplib2.Http()
    http.add_credentials('api', MAILGUN_API_KEY)

    url = 'https://api.mailgun.net/v3/{}/messages'.format(MAILGUN_DOMAIN_NAME)
    data = {
        'from': 'Example Sender <mailgun@{}>'.format(MAILGUN_DOMAIN_NAME),
        'to': recipient,
        'subject': 'This is an example email from Mailgun',
        'text': 'Test message from Mailgun'
    }

    resp, content = http.request(url, 'POST', urlencode(data))

    if resp.status != 200:
        raise RuntimeError(
            'Mailgun API error: {} {}'.format(resp.status, content))

Sending an HTML and text email

Sending a message with HTML and text parts:

def send_complex_message(recipient):
    http = httplib2.Http()
    http.add_credentials('api', MAILGUN_API_KEY)

    url = 'https://api.mailgun.net/v3/{}/messages'.format(MAILGUN_DOMAIN_NAME)
    data = {
        'from': 'Example Sender <mailgun@{}>'.format(MAILGUN_DOMAIN_NAME),
        'to': recipient,
        'subject': 'This is an example email from Mailgun',
        'text': 'Test message from Mailgun',
        'html': '<html>HTML <strong>version</strong> of the body</html>'
    }

    resp, content = http.request(url, 'POST', urlencode(data))

    if resp.status != 200:
        raise RuntimeError(
            'Mailgun API error: {} {}'.format(resp.status, content))

Sample response:

{
    "message": "Queued. Thank you.",
    "id": "<20111114174239.25659.5817@samples.mailgun.org>"
}

Learning more

For more detailed examples and information, including how to track and route messages, see Mailgun's documentation.

Send feedback about...

App Engine standard environment for Python