Python SDK for Mailgun

1.6.0 · active · verified Sat Apr 11

The `mailgun` Python SDK provides a convenient interface for interacting with the Mailgun email API. It simplifies sending, receiving, and managing emails, domains, and webhooks programmatically. The library is actively maintained, with regular minor releases adding new API endpoint support and features like async client functionality. The current stable version is 1.6.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Mailgun client and send a basic text email using environment variables for API key and domain. Ensure `MAILGUN_API_KEY`, `MAILGUN_DOMAIN`, and optionally `MAILGUN_API_BASE_URL` are set. Remember to replace `test@example.com` with an authorized recipient.

import os
from mailgun.client import Client

def send_simple_message():
    api_key = os.environ.get('MAILGUN_API_KEY', 'YOUR_MAILGUN_API_KEY')
    domain = os.environ.get('MAILGUN_DOMAIN', 'YOUR_MAILGUN_DOMAIN')
    # Use the appropriate API base URL for your region (US or EU)
    # For US: api_base_url = "https://api.mailgun.net/v3"
    # For EU: api_base_url = "https://api.eu.mailgun.net/v3"
    api_base_url = os.environ.get('MAILGUN_API_BASE_URL', "https://api.mailgun.net/v3")

    if not api_key or not domain:
        print("Please set MAILGUN_API_KEY and MAILGUN_DOMAIN environment variables.")
        return

    client = Client(auth=("api", api_key), api_url=f"{api_base_url}/{domain}")

    try:
        response = client.send_message(
            from_email="Excited User <mailgun@{}>.format(domain)",
            to_emails=["test@example.com"], # Replace with a verified recipient
            subject="Hello from Mailgun Python SDK",
            text="Congratulations, you just sent an email with Mailgun Python SDK!"
        )
        print(f"Mailgun API response: {response.status_code} - {response.json()}")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    send_simple_message()

view raw JSON →