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.
pip install mailgunVerified import paths — ran on the pinned version, not inferred.
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.
Set the `api_url` parameter in `mailgun.client.Client` or `mailgun.client.AsyncClient` to match your Mailgun domain's region (e.g., `https://api.eu.mailgun.net/v3` for EU).
Add and verify recipient email addresses in your Mailgun dashboard under the 'Sandbox Domains' section.
Ensure the `from_email` parameter in `send_message` uses an email address that belongs to a domain you have configured and verified in Mailgun.
When using `AsyncClient`, ensure your code is within an `async` function and all client method calls are `await`ed. For synchronous operations, use the `Client`.
Install the library using pip: `pip install mailgun`
Double-check your API key (ensure it's the private/sending key starting with 'key-'), your domain name, and the API endpoint URL (e.g., `https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages` for US or `https://api.eu.mailgun.net/v3/YOUR_DOMAIN_NAME/messages` for EU). Verify your domain in the Mailgun dashboard.
Check your Mailgun 'Logs' or 'Events' dashboard for detailed delivery failures and error messages. If using a sandbox domain, ensure recipient emails are added as 'Authorized Recipients'. Verify your sending domain and ensure the 'from' address is valid and linked to your domain.
Ensure all email addresses are correctly formatted (e.g., `Sender Name <sender@example.com>` or `sender@example.com`) and do not contain typos or extra characters. Confirm the 'from' email address is allowed for your sending domain in Mailgun.
Use `from mailgun import Mailgun` to import the class, then instantiate it: `client = Mailgun(api_key='YOUR_API_KEY', domain='YOUR_DOMAIN')`