Python SDK for Mailgun
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
- gotcha Mailgun operates in different regions (US and EU). Using the incorrect API base URL (`api_url` in the client constructor) for your domain's region will result in API errors.
- gotcha When using a Mailgun sandbox domain, all recipient email addresses must be manually added and verified within the Mailgun control panel before you can send emails to them. Attempts to send to unverified recipients will fail.
- gotcha The 'from' email address used when sending messages must be associated with your verified Mailgun domain or sandbox domain. Sending from an unverified 'from' address will result in an API error.
- gotcha The `AsyncClient` (introduced in v1.5.0) provides asynchronous functionality but requires `await` for all method calls, consistent with `asyncio` patterns. Mixing synchronous `Client` usage with `AsyncClient` methods or forgetting `await` will lead to runtime errors.
Install
-
pip install mailgun
Imports
- Client
from mailgun.client import Client
- AsyncClient
from mailgun.client import AsyncClient
Quickstart
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()