### Async GET Request Example Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-async-client.md Demonstrates how to send asynchronous GET requests using the AsyncClient. This includes fetching all domain lists and retrieving events with specific filters and a target domain. ```python import asyncio from mailgun.client import AsyncClient async def main(): async with AsyncClient(auth=("api", "key")) as client: # Get all domains response = await client.domainlist.get() print(response.json()) # Get with filters response = await client.events.get( domain="example.com", filters={"limit": 10} ) print(response.json()) asyncio.run(main()) ``` -------------------------------- ### Clone Repository and Install Locally Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Install the Mailgun SDK locally by cloning the repository and then installing it using pip. This is useful for development or testing specific versions. ```bash git clone https://github.com/mailgun/mailgun-python cd mailgun-python ``` ```bash pip install . ``` -------------------------------- ### Install with Conda and Make Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Install the Mailgun SDK locally on Unix platforms using `conda` and `make`. This command automates the installation process. ```bash make install ``` -------------------------------- ### Mailgun CREATE (POST) Request Examples Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-endpoint.md Provides examples for using the create() method to send emails, send emails with attachments, create bounce records, and create webhooks with JSON headers. ```python # Send an email response = client.messages.create( domain="example.com", data={ "from": "sender@example.com", "to": "recipient@example.com", "subject": "Hello", "text": "This is a test email" } ) # Send with attachments from pathlib import Path files = [("attachment", ("report.pdf", Path("report.pdf").read_bytes()))] response = client.messages.create( domain="example.com", data={"from": "...", "to": "...", "subject": "..."}, files=files ) # Create a bounce record response = client.bounces.create( domain="example.com", data={"address": "test@example.com", "code": 550, "error": "User unknown"} ) # Create a webhook with JSON headers response = client.domains_webhooks.create( domain="example.com", data={"event_types": "clicked,opened", "url": "https://example.com/webhook"}, headers={"Content-Type": "application/json"} ) ``` -------------------------------- ### Mailgun GET Request Examples Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-endpoint.md Demonstrates how to use the get() method to retrieve data from various Mailgun endpoints, including fetching all domains, filtering results, and retrieving domain-specific data or events. ```python from mailgun.client import Client client = Client(auth=("api", "key")) # Get all domains response = client.domainlist.get() print(response.status_code) print(response.json()) # Get domains with filters response = client.domainlist.get(filters={"skip": 0, "limit": 10}) # Get domain-specific data response = client.domains.get(domain="example.com") # Get events with query parameters response = client.events.get( domain="example.com", filters={"recipient": "user@example.com", "limit": 25} ) ``` -------------------------------- ### Example API URL Constructions Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-config.md Shows various examples of constructed API request URLs for different HTTP methods and endpoints. ```text GET /v3/domains GET /v3/domains/example.com/messages GET /v1/dkim/keys POST /v4/address/validate POST /v3/example.com/bounces ``` -------------------------------- ### Install Mailgun SDK with pip Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Install the Mailgun SDK for Python using pip. This is the standard method for adding the library to your project. ```bash pip install mailgun ``` -------------------------------- ### Async PUT Request Example Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-async-client.md Example of sending an asynchronous PUT request to update a domain's configuration, such as disabling spam action. ```python response = await client.domains.put( domain="example.com", data={"spam_action": "disabled"} ) ``` -------------------------------- ### URL Construction Example Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-config.md Illustrates the basic pattern for constructing API URLs, including version, path, domain, and keys. ```text {api_url}/{version}/{path}/{domain}/{keys} ``` -------------------------------- ### File Upload Example Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/README.md Illustrates how to send attachments and files with a message creation request, specifying file names and content. ```python from pathlib import Path files = [ ("attachment", ("report.pdf", Path("report.pdf").read_bytes())), ("signature", ("sig.png", Path("sig.png").read_bytes())) ] response = client.messages.create( domain="example.com", data={...}, files=files ) ``` -------------------------------- ### Get Account Usage Metrics Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves account usage metrics for a specified date range and resolution. Requires setting start and end dates, resolution, duration, dimensions, and metrics. ```python def post_analytics_usage_metrics() -> None: """ # Usage Metrics # POST /analytics/usage/metrics :return: """ data = { "start": "Sun, 08 Jun 2025 00:00:00 +0000", "end": "Tue, 08 Jul 2025 00:00:00 +0000", "resolution": "day", "duration": "1m", "dimensions": ["time"], "metrics": [ "accessibility_count", "accessibility_failed_count", "domain_blocklist_monitoring_count", "email_preview_count", "email_preview_failed_count", "email_validation_bulk_count", "email_validation_count", "email_validation_list_count", "email_validation_mailgun_count", "email_validation_mailjet_count", "email_validation_public_count", "email_validation_single_count", "email_validation_valid_count", "image_validation_count", "image_validation_failed_count", "ip_blocklist_monitoring_count", "link_validation_count", "link_validation_failed_count", "processed_count", "seed_test_count", ], "include_subaccounts": True, "include_aggregates": True, } req = client.analytics_usage_metrics.create(data=data) print(req.json()) ``` -------------------------------- ### Get All Webhooks Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of all configured webhooks. ```APIDOC ## GET /domains//webhooks ### Description Retrieves a list of all configured webhooks for a domain. ### Method GET ### Endpoint /domains//webhooks ### Response #### Success Response (200) - **(response body)** - The JSON response containing a list of webhooks. ``` -------------------------------- ### Dynamic Routing Examples Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/README.md Illustrates the structure of constructed URLs for different API endpoints based on the SDK's dynamic routing engine. ```text /v3/{domain}/messages /v1/dkim/keys /v4/address/validate ``` -------------------------------- ### Pagination Example Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/README.md Shows how to retrieve paginated data from an endpoint, including accessing page information and the next page URL. ```python # Get first page response = client.domainlist.get(filters={"skip": 0, "limit": 10}) data = response.json() # Access pages info pages = data.get("pages", {}) next_page = pages.get("next") ``` -------------------------------- ### Example of EXACT_ROUTES Configuration Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-config.md Illustrates the structure of `EXACT_ROUTES`, a dictionary mapping endpoint names to their corresponding API versions and path tuples. ```python # Example from routes.py EXACT_ROUTES = { "messages": ("v3", ("messages",)), "domainlist": ("v4", ("domainlist",)), "dkim_keys": ("v1", ("dkim", "keys")), "bounce_classification": ("v2", ("bounce-classification", "metrics")), ... } ``` -------------------------------- ### Get domains Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of all supported domains. ```APIDOC ## Get domains ### Description Retrieves a list of all supported domains associated with the account. ### Method GET ### Endpoint /domains ### Response #### Success Response (200) - **domains** (list) - A list of domain objects. ### Request Example ```python data = client.domainlist.get() print(data.json()) ``` ``` -------------------------------- ### Get All Template Versions Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves all versions of a specified template. Requires the domain and template name. ```python req = client.templates.get(domain=domain, template_name="template.name1", versions=True) print(req.json()) ``` -------------------------------- ### Get All Domain Webhooks Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of all configured webhooks for the domain. ```python req = client.domains_webhooks.get() ``` -------------------------------- ### Using APIVersion Enum Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/types.md Shows how to use the APIVersion enumeration to get the version string, iterate through versions, and check for support. ```python from mailgun.client import APIVersion # Access version string version = APIVersion.V3.value # "v3" # Iterate versions for api_ver in APIVersion: print(api_ver.value) # String comparison if "v3" in [v.value for v in APIVersion]: print("v3 is supported") ``` -------------------------------- ### Type Hinting Examples Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/README.md Demonstrates the use of type hints for synchronous and asynchronous response objects, improving code clarity and enabling static analysis. ```python # Type hints are available response: requests.Response = client.messages.create(data={...}) async_response: httpx.Response = await async_client.messages.create(data={...}) ``` -------------------------------- ### Get all template's versions Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves all versions of a specified template within a domain. ```APIDOC ## Get all template's versions ### Description Retrieves all versions of a specified template within a domain. ### Method GET ### Endpoint /v1/domains/{domain}/templates/{template_name}/versions ### Parameters #### Path Parameters - **domain** (string) - Required - The domain name. - **template_name** (string) - Required - The name of the template. #### Query Parameters - **versions** (boolean) - Optional - If true, returns all versions of the template. ``` -------------------------------- ### Async DELETE Request Example Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-async-client.md Demonstrates sending an asynchronous DELETE request to remove a resource, such as a mailing list address. ```python response = await client.lists.delete( domain="example.com", address="team@example.com" ) ``` -------------------------------- ### Initialize AsyncClient and Send Message Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-async-client.md Demonstrates basic initialization of the AsyncClient with authentication and sending a message. It's recommended to use the async context manager for proper resource management. ```python import asyncio from mailgun.client import AsyncClient async def main(): # Basic initialization async with AsyncClient(auth=("api", "your-key")) as client: response = await client.messages.create( domain="example.com", data={"to": "user@example.com", "from": "sender@example.com"} ) print(response.json()) # Run async function asyncio.run(main()) ``` -------------------------------- ### Getting Domain Tracking Settings Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Fetch the tracking settings for a specific domain using the domains_tracking.get endpoint. ```python response = client.domains_tracking.get(domain="example.com") ``` -------------------------------- ### Profile Cold-Boot Initialization Source: https://github.com/mailgun/mailgun-python/blob/main/PERFORMANCE.md Run tests to profile the cold-boot initialization performance of the SDK. ```bash python tests/test_boot.py ``` -------------------------------- ### Get Domain Details Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves detailed information for a specific domain by its name. Replace 'python.test.com' with your actual domain name. ```python domain_name = "python.test.com" data = client.domains.get(domain_name=domain_name) print(data.json()) ``` -------------------------------- ### Mailgun PUT Request Examples Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-endpoint.md Illustrates how to use the put() method to update domain settings and DKIM authority for a specified domain. ```python # Update domain settings response = client.domains.put( domain="example.com", data={ "name": "example.com", "spam_action": "disabled", "wildcard": "true" } ) # Update DKIM authority response = client.domains_dkimauthority.put( domain="example.com", data={"self": "false"} ) ``` -------------------------------- ### Get Account Usage Metrics Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Retrieve account usage metrics, such as email validation and preview counts. Specify the start and end dates for the period you want to query. ```python response = client.analytics_usage_metrics.create( data={ "start": "...", "end": "...", "metrics": ["email_validation_count", "email_preview_count", ...] } ) ``` -------------------------------- ### Recommended Production Logging Setup Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/configuration.md Configure basic logging to INFO level for production environments. This provides essential operational visibility without excessive detail, suitable for monitoring application behavior. ```python import logging import os from mailgun.client import Client # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) ``` -------------------------------- ### Async POST Request Example (Send Email) Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-async-client.md Shows how to send an asynchronous POST request to create a message, specifically for sending an email. It includes setting the sender, recipient, subject, and body. ```python import asyncio from mailgun.client import AsyncClient async def main(): async with AsyncClient(auth=("api", "key")) as client: # Send email asynchronously response = await client.messages.create( domain="example.com", data={ "from": "sender@example.com", "to": "recipient@example.com", "subject": "Async Email", "text": "This was sent asynchronously!" } ) print(response.json()) asyncio.run(main()) ``` -------------------------------- ### Dockerfile for Mailgun Application Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/configuration.md A sample Dockerfile to containerize a Python application that uses the Mailgun SDK. It sets up environment variables and installs dependencies. ```dockerfile # Dockerfile FROM python:3.10-slim ENV MAILGUN_API_KEY="" ENV MAILGUN_API_URL="https://api.mailgun.net" ENV MAILGUN_DOMAIN="" ENV MAILGUN_TIMEOUT="30" WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY app.py . CMD ["python", "app.py"] ``` -------------------------------- ### Validate Mailgun Email Address (GET) Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Validate an email address using a GET request. ```python response = client.addressvalidate.get(address="test@example.com") ``` -------------------------------- ### Client Initialization with Timeout Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/types.md Demonstrates how to initialize the Mailgun Client with different timeout configurations. The tuple format is recommended for production environments. ```python from mailgun.client import Client # Single timeout client = Client(auth=("api", "key"), timeout=30.0) # Connect/read tuple (recommended for production) client = Client(auth=("api", "key"), timeout=(10.0, 60.0)) # No timeout (deprecated) client = Client(auth=("api", "key"), timeout=None) ``` -------------------------------- ### Client Initialization (Synchronous) Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/README.md Demonstrates how to initialize the synchronous Mailgun client using API keys and best practices for context management. ```APIDOC ## Client Initialization (Synchronous) ### Description Initializes the synchronous Mailgun client using API keys. It is recommended to use a context manager for proper resource handling. ### Method `Client(auth, api_url=None, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from mailgun.client import Client import os auth = ("api", os.environ["MAILGUN_API_KEY"]) client = Client(auth=auth) # Best practice: use context manager with Client(auth=auth) as client: response = client.messages.create(data={{...}}) ``` ### Response #### Success Response (200) Returns a client object that can be used to interact with the Mailgun API. #### Response Example None ``` -------------------------------- ### Get Tag Limit Information Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Retrieve information about the limits associated with account tags. This is a simple GET request with no parameters required. ```python response = client.analytics_tags_limits.get() ``` -------------------------------- ### Set Environment Variables for Testing Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Export necessary environment variables required for running tests and examples, including API key, domain, and sender/recipient details. ```bash export APIKEY="API_KEY" # pragma: allowlist secret export DOMAIN="DOMAIN_NAME" export MESSAGES_FROM="Name Surname " export MESSAGES_TO="Name Surname " export MESSAGES_CC="Name Surname " export DOMAINS_DEDICATED_IP="127.0.0.1" export MAILLIST_ADDRESS="everyone@mailgun.domain.com" export VALIDATION_ADDRESS_1="test1@i.ua" export VALIDATION_ADDRESS_2="test2@gmail.com" export MAILGUN_EMAIL="username@example.com" export USER_ID="123456789012345678901234" export USER_NAME="Name Surname" export ROLE="admin" ``` -------------------------------- ### Secure Credential Handling Example Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/configuration.md Demonstrates that the Mailgun SDK automatically redacts API keys in memory dumps and exception tracebacks for enhanced security. ```python client = Client(auth=("api", "secret-key")) # Safe output - key is redacted print(client) # print(repr(client)) # # Exception traceback also redacts the key try: raise Exception("Client state") except: import traceback traceback.print_exc() # Key not exposed in traceback ``` -------------------------------- ### Get Templates Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of templates for a given domain, with optional filtering. Requires the domain and can accept parameters like 'limit'. ```python domain: str = os.environ["DOMAIN"] params = {"limit": 1} req = client.templates.get(domain=domain, filters=params) print(req.json()) ``` -------------------------------- ### Endpoint GET Method Signature Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-endpoint.md Signature for the GET method, used to retrieve resources from an endpoint. It accepts optional filters and a domain parameter. ```python def get( self, filters: Mapping[str, str | Any] | None = None, domain: str | None = None, **kwargs: Any, ) -> Response ``` -------------------------------- ### Migrate Sync to Async Mailgun Client Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-async-client.md Provides a direct comparison and conversion example for migrating from the synchronous Mailgun Client to the asynchronous AsyncClient. Note the use of `async with` and `asyncio.run`. ```python # Synchronous version from mailgun.client import Client client = Client(auth=("api", "key")) response = client.messages.create(data={...}) # Asynchronous version from mailgun.client import AsyncClient import asyncio async def send_email(): async with AsyncClient(auth=("api", "key")) as client: response = await client.messages.create(data={...}) return response.json() result = asyncio.run(send_email()) ``` -------------------------------- ### Getting and Updating Domain Connection Settings Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Retrieve or modify the connection settings for a domain using the domains_connection endpoint. Supports both GET and PUT requests. ```python response = client.domains_connection.get(domain="example.com") response = client.domains_connection.put( domain="example.com", data={"require_tls": "true"} ) ``` -------------------------------- ### Async GET Request Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-async-client.md Sends an asynchronous GET request. This method can be used to retrieve data, often with filtering capabilities. It supports optional query parameters and a target domain. ```APIDOC ## GET ### Description Sends an asynchronous GET request to retrieve data. Supports optional filters and a target domain. ### Method GET ### Endpoint (Varies based on the client attribute, e.g., /domainlist, /events) ### Parameters #### Query Parameters - **filters** (Mapping[str, str | Any] | None) - Optional - Query parameters for filtering results. - **domain** (str | None) - Optional - The target domain for the request. - **kwargs** (Any) - Optional - Additional keyword arguments for the request. ### Response #### Success Response (200) - **httpx.Response** - The HTTP response object containing the result of the GET request. ### Request Example ```python import asyncio from mailgun.client import AsyncClient async def main(): async with AsyncClient(auth=("api", "key")) as client: # Get all domains response = await client.domainlist.get() print(response.json()) # Get with filters response = await client.events.get( domain="example.com", filters={"limit": 10} ) print(response.json()) asyncio.run(main()) ``` ``` -------------------------------- ### Get Events by Recipient with Filters Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves events filtered by recipient, date range, and limit. The 'begin' parameter expects a formatted date string. ```python params = { "begin": "Tue, 24 Nov 2025 09:00:00 -0000", "limit": 10, "recipient": "user@example.com", } req = client.events.get(filters=params) ``` -------------------------------- ### Initialize Synchronous and Asynchronous Clients Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/configuration.md Demonstrates how to initialize both synchronous and asynchronous Mailgun clients with authentication, API URL, and timeout configurations. The asynchronous client also shows how to pass custom httpx client arguments. ```python from mailgun.client import Client, AsyncClient # Synchronous client client = Client( auth=("api", "your-api-key"), api_url="https://api.mailgun.net", # or "https://api.eu.mailgun.net" timeout=60.0, # seconds ) # Asynchronous client async_client = AsyncClient( auth=("api", "your-api-key"), api_url="https://api.mailgun.net", timeout=(10.0, 60.0), # (connect, read) client_kwargs={} ) ``` -------------------------------- ### URL Building Example Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-endpoint.md Illustrates how the Mailgun SDK automatically constructs endpoint URLs using base URL, API version, endpoint keys, domain placeholders, and dynamic parameters. ```text POST /v3/{domain}/messages POST /v1/dkim/keys GET /v4/address/validate ``` -------------------------------- ### domains (get) Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Retrieve details for a specific domain. ```APIDOC ## GET /v3/domains/{domain} ### Description Get details for a specific domain. ### Method GET ### Endpoint `/v3/domains/{domain}` ### Parameters #### Path Parameters - **domain** (string) - Required - The domain to retrieve details for. ### Response #### Success Response (200) JSON object containing the domain's details. ``` -------------------------------- ### domains_dkimauthority Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Get or update the DKIM authority settings for a domain. ```APIDOC ## PUT /v3/domains/{domain}/dkim_authority ### Description Get or update DKIM authority settings. ### Method PUT ### Endpoint `/v3/domains/{domain}/dkim_authority` ### Parameters #### Path Parameters - **domain** (string) - Required - The domain to update DKIM authority for. #### Request Body - **self** (string) - Optional - Whether to use self-signed DKIM keys (e.g., "false"). ### Request Example ```json { "self": "false" } ``` ### Response #### Success Response (200) Details of the updated DKIM authority settings. ``` -------------------------------- ### Initialize Config with Custom API URL Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-config.md Instantiate the `Config` class with an optional custom API URL. Useful for specifying the EU region or for local testing. ```python from mailgun.client import Config # Default US configuration config = Config() # Custom EU configuration config_eu = Config(api_url="https://api.eu.mailgun.net") # Custom localhost (testing) config_local = Config(api_url="http://localhost:8080") ``` -------------------------------- ### Get all inbox Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves all inbox test results for a given domain. ```APIDOC ## Get all inbox ### Description Retrieves all inbox test results for a given domain. ### Method GET ### Endpoint /v1/domains/{domain}/inbox/tests ### Parameters #### Path Parameters - **domain** (string) - Required - The domain name. ``` -------------------------------- ### Get Tracking Settings Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves the tracking settings for a specific domain. ```APIDOC ## GET /domains//tracking ### Description Retrieves the tracking settings for a specific domain. ### Method GET ### Endpoint /domains//tracking ### Parameters #### Path Parameters - **domain** (string) - Required - The domain for which to retrieve tracking settings. ### Response #### Success Response (200) - **(response body)** - The JSON response containing tracking settings. ``` -------------------------------- ### Set Up Development Environment with Conda Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Set up a basic or full development environment for the Mailgun Python SDK using `conda` and `make` commands on Linux or macOS. ```bash git clone https://github.com/mailgun/mailgun-python cd mailgun-python ``` ```bash make dev conda activate mailgun ``` ```bash make dev-full conda activate mailgun-dev ``` -------------------------------- ### Get Domain Connections Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves connection information for a specific domain. ```APIDOC ## GET /domains//connection ### Description Retrieves connection information for a specific domain. ### Method GET ### Endpoint /domains//connection ### Parameters #### Path Parameters - **domain** (string) - Required - The domain for which to retrieve connection information. ### Response #### Success Response (200) - **(response body)** - The JSON response containing connection details. ``` -------------------------------- ### Initialize Mailgun Client Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-client.md Instantiate the synchronous Mailgun Client. Basic initialization requires authentication credentials. Customization options include specifying the API URL and request timeouts. ```python from mailgun.client import Client import os # Basic initialization auth = ("api", os.environ["APIKEY"]) client = Client(auth=auth) # With custom EU endpoint client = Client( auth=("api", "your-api-key"), api_url="https://api.eu.mailgun.net" ) # With custom timeouts (connect_timeout, read_timeout) client = Client( auth=auth, timeout=(10.0, 60.0) ) ``` -------------------------------- ### Authenticate using Environment Variable Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/configuration.md Illustrates the recommended method for authentication by retrieving the API key from an environment variable. ```python import os # From environment variable (recommended) api_key = os.environ["MAILGUN_API_KEY"] client = Client(auth=("api", api_key)) ``` -------------------------------- ### domains_connection Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Get or update domain connection settings, such as TLS requirements. ```APIDOC ## GET/PUT /v3/domains/{domain}/connection ### Description Get or update domain connection settings. ### Method GET, PUT ### Endpoint `/v3/domains/{domain}/connection` ### Parameters #### Path Parameters - **domain** (string) - Required - The domain to manage connection settings for. #### Request Body (for PUT) - **require_tls** (string) - Optional - Whether to require TLS for connections (e.g., "true"). ### Request Example (PUT) ```json { "require_tls": "true" } ``` ### Response #### Success Response (200) Details of the domain's connection settings. ``` -------------------------------- ### AsyncClient Initialization (Asynchronous) Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/README.md Shows how to initialize the asynchronous Mailgun client for non-blocking API calls. ```APIDOC ## AsyncClient Initialization (Asynchronous) ### Description Initializes the asynchronous Mailgun client for making non-blocking API calls. It is recommended to use a context manager for proper resource handling. ### Method `AsyncClient(auth, api_url=None, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from mailgun.client import AsyncClient import asyncio async def main(): async with AsyncClient(auth=("api", "key")) as client: response = await client.messages.create(data={{...}}) asyncio.run(main()) ``` ### Response #### Success Response (200) Returns an asynchronous client object that can be used to interact with the Mailgun API. #### Response Example None ``` -------------------------------- ### Events Get Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/README.md Retrieves events associated with a domain, with support for filtering. ```APIDOC ## Events Get ### Description Retrieves events associated with a specific Mailgun domain. Supports filtering to narrow down the results. ### Method `client.events.get(domain, filters=None)` ### Parameters #### Path Parameters None #### Query Parameters - **domain** (string) - Required - The domain to retrieve events for. - **filters** (dict) - Optional - A dictionary of filters to apply to the event retrieval. Common filters include: - **limit** (int) - The maximum number of events to return. - **recipient** (string) - Filter events by recipient email address. ### Request Example ```python response = client.events.get( domain="example.com", filters={ "limit": 25, "recipient": "user@example.com" } ) ``` ### Response #### Success Response (200) Returns a response object containing a list of events matching the specified criteria. #### Response Example None ``` -------------------------------- ### Using AsyncClient with Async Context Manager Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-async-client.md Demonstrates the recommended way to use AsyncClient with an `async with` statement, ensuring automatic cleanup of resources. This example sends an email asynchronously. ```python import asyncio from mailgun.client import AsyncClient async def main(): # Best practice: Use async context manager async with AsyncClient(auth=("api", "key")) as client: response = await client.messages.create( domain="example.com", data={ "from": "sender@example.com", "to": "recipient@example.com", "subject": "Async Test", "text": "Hello async world!" } ) print(response.json()) # Client automatically closed here asyncio.run(main()) ``` -------------------------------- ### GET /routes/{route_id} Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a specific route by its ID for a given domain. ```APIDOC ## GET /routes/{route_id} ### Description Retrieves a specific route by its ID for a given domain. ### Method GET ### Endpoint /routes/{route_id} ### Parameters #### Path Parameters - **domain** (string) - Required - The domain associated with the route. - **route_id** (string) - Required - The ID of the route to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the route. - **priority** (integer) - The priority of the route. - **description** (string) - The description of the route. - **expression** (string) - The expression used to match messages. - **action** (array of strings) - The actions performed on matched messages. ``` -------------------------------- ### Initialize Mailgun Client with Production Settings Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/configuration.md Initializes the Mailgun client using environment variables for API key, URL, and timeout. It's recommended to use a context manager for production environments. ```python import os from mailgun.client import Client api_key = os.environ["MAILGUN_API_KEY"] api_url = os.environ.get("MAILGUN_API_URL", "https://api.mailgun.net") timeout = float(os.environ.get("MAILGUN_TIMEOUT", "30")) client = Client( auth=("api", api_key), api_url=api_url, timeout=(10.0, timeout) # Fast connect, patient read ) ``` -------------------------------- ### Get Mailgun Template Versions Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Retrieve all versions of a specific email template. ```python response = client.templates.get( domain="example.com", template_name="welcome", versions=True ) ``` -------------------------------- ### Get Mailgun Route Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Retrieve a specific route by its ID for a given domain. ```python response = client.routes.get(domain="example.com", route_id="id") ``` -------------------------------- ### Domain Sanitization with SecurityGuard Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-config.md Demonstrates how to sanitize domain names to prevent path traversal issues using the SecurityGuard class. ```python from mailgun.client import SecurityGuard # Domain sanitization removes path traversal characters safe_domain = SecurityGuard.sanitize_domain("../evil") # Raises ValueError safe_domain = SecurityGuard.sanitize_domain("example.com") # Returns "example.com" ``` -------------------------------- ### Get a user's details Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves the details of a specific user based on their ID. ```APIDOC ## Get a user's details ### Description Retrieves the details of a specific user based on their ID. ### Method GET ### Endpoint /v1/users/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. ``` -------------------------------- ### Client Constructor Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-client.md Initializes a new synchronous `Client` instance for interacting with the Mailgun API. It supports authentication, custom API URLs, and request timeouts. ```APIDOC ## Client Constructor ### Description Initializes a new synchronous Client instance for API interaction. ### Method Signature ```python def __init__( self, auth: tuple[str, str] | None = None, **kwargs: Any, ) -> None ``` ### Parameters #### Keyword Arguments - **auth** (`tuple[str, str] | None`) - Optional - Authentication tuple of (username, api_key). Use `("api", "YOUR_KEY")`. - **api_url** (`str`) - Optional - Base URL for API calls. Use `https://api.eu.mailgun.net` for EU regions. Defaults to `https://api.mailgun.net`. - **timeout** (`float | tuple[float, float] | None`) - Optional - Request timeout in seconds or (connect, read) tuple. Defaults to `60.0`. - **api_version** (`str`) - Optional - Deprecated parameter. SDK handles versioning automatically. ### Returns - `Client` instance ready for API calls. ### Example ```python from mailgun.client import Client import os # Basic initialization auth = ("api", os.environ["APIKEY"]) client = Client(auth=auth) # With custom EU endpoint client = Client( auth=("api", "your-api-key"), api_url="https://api.eu.mailgun.net" ) # With custom timeouts (connect_timeout, read_timeout) client = Client( auth=auth, timeout=(10.0, 60.0) ) # Using context manager (recommended for production) with Client(auth=auth) as client: response = client.messages.create(data={"to": "user@example.com"}) ``` ``` -------------------------------- ### Get Mailgun IP Pools Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Retrieve a list of IP pools for a given domain. ```python response = client.ippools.get(domain="example.com") ``` -------------------------------- ### Send Email using Mailgun Client with Context Manager Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/configuration.md Demonstrates sending an email using the Mailgun client within a context manager, ensuring proper resource management. Includes error handling and logging. ```python import os from mailgun.client import Client import logging logger = logging.getLogger(__name__) api_key = os.environ["MAILGUN_API_KEY"] api_url = os.environ.get("MAILGUN_API_URL", "https://api.mailgun.net") # ALWAYS use context manager for production def send_email(to_addr, subject, body): try: with Client(auth=("api", api_key), api_url=api_url, timeout=(10.0, 30.0)) as client: response = client.messages.create( domain="example.com", data={ "from": "noreply@example.com", "to": to_addr, "subject": subject, "text": body } ) if response.status_code == 200: logger.info(f"Email sent: {response.json()['id']}") return True else: logger.error(f"Send failed: {response.status_code}") return False except Exception as e: logger.exception("Email sending error") # Implement fallback: queue, retry, etc. return False ``` -------------------------------- ### Client Initialization with Timeouts Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/README.md Configure the Mailgun client with different timeout settings. Use a single float for both connect and read timeouts, or a tuple for separate connect and read timeouts. ```python # Single timeout (apply to connect + read) Client(auth=auth, timeout=30.0) ``` ```python # Tuple timeout (connect, read separately) Client(auth=auth, timeout=(10.0, 60.0)) ``` -------------------------------- ### Get users on an account Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of users on the account, with options to filter by role and pagination. ```APIDOC ## Get users on an account ### Description Retrieves a list of users on the account, with options to filter by role and pagination. ### Method GET ### Endpoint /v1/users ### Parameters #### Query Parameters - **role** (string) - Optional - Filters users by their role (e.g., "admin"). - **limit** (string) - Optional - The maximum number of users to return. - **skip** (string) - Optional - The number of users to skip before returning results. ``` -------------------------------- ### Lazy Initialization of Internal httpx Client Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-async-client.md Shows how the internal httpx.AsyncClient is lazily initialized on first use, optimizing startup time and enabling features like automatic retries and connection pooling. ```python async with AsyncClient(auth=auth) as client: # First access initializes the internal httpx.AsyncClient response = await client.messages.create(data={...}) # Subsequent calls reuse the same client response2 = await client.domains.get() ``` -------------------------------- ### AsyncClient as Async Context Manager Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Demonstrates using the AsyncClient as an asynchronous context manager, which automatically handles connection closing. This is the recommended way to use the async client. ```python import asyncio import os from mailgun.client import AsyncClient async def main(): auth = ("api", os.environ["APIKEY"]) async with AsyncClient(auth=auth) as client: result = await client.domainlist.get() print(result) asyncio.run(main()) ``` -------------------------------- ### GET /templates Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of email templates for a given domain. Supports filtering and pagination. ```APIDOC ## GET /templates ### Description Retrieves a list of email templates for a given domain. Supports filtering and pagination. ### Method GET ### Endpoint /templates ### Parameters #### Path Parameters - **domain** (string) - Required - The domain for which to retrieve templates. #### Query Parameters - **limit** (integer) - Optional - The maximum number of templates to return. ### Response #### Success Response (200) - **items** (array) - A list of template objects. - **next_page** (string) - URL for the next page of results, if any. ``` -------------------------------- ### Create a Route Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Creates a new route for handling incoming messages. Requires priority, description, expression, and action parameters. ```python domain: str = os.environ["DOMAIN"] data = { "priority": 0, "description": "Sample route", "expression": f"match_recipient('.*@{domain}')", "action": ["forward('http://myhost.com/messages/')", "stop()"], } req = client.routes.create(domain=domain, data=data) print(req.json()) ``` -------------------------------- ### GET /lists/{address}/members Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a paginated list of members for a specific mailing list. ```APIDOC ## GET /lists/{address}/members ### Description Retrieves a paginated list of members for a specific mailing list. ### Method GET ### Endpoint /lists/{address}/members ### Parameters #### Path Parameters - **domain** (string) - Required - The domain of the mailing list. - **address** (string) - Required - The email address of the mailing list. ### Response #### Success Response (200) - **items** (array) - A list of mailing list members. - **next_page** (string) - URL for the next page of results, if any. ``` -------------------------------- ### GET /unsubscribes Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of all unsubscribed email addresses for a given domain. Supports pagination. ```APIDOC ## GET /unsubscribes ### Description Retrieves a list of all unsubscribed email addresses for a given domain. Supports pagination. ### Method GET ### Endpoint /unsubscribes ### Parameters #### Query Parameters - **domain** (string) - Required - The domain for which to retrieve unsubscribes. ### Response #### Success Response (200) - **items** (array) - A list of unsubscribe entries. - **next_page** (string) - URL for the next page of results, if any. ``` -------------------------------- ### Get a Route by ID Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a specific route by its ID. Requires the domain and the route ID. ```python domain: str = os.environ["DOMAIN"] req = client.routes.get(domain=domain, route_id="xxxxxxxx") print(req.json()) ``` -------------------------------- ### Get Events by Recipient Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves events filtered by recipient, with options for date range and limit. ```APIDOC ## GET /events ### Description Retrieves events filtered by recipient, with options for date range and limit. ### Method GET ### Endpoint /events ### Parameters #### Query Parameters - **begin** (string) - Optional - The start of the time range for events (e.g., "Tue, 24 Nov 2025 09:00:00 -0000"). - **limit** (integer) - Optional - The maximum number of events to return. - **recipient** (string) - Required - The email address of the recipient. ### Response #### Success Response (200) - **(response body)** - The JSON response containing a list of events matching the filters. ``` -------------------------------- ### Send Email with Attachments Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Demonstrates sending an email with attachments. It's recommended to open files in binary mode using `read_bytes()`. ```python from pathlib import Path files = [("attachment", ("report.pdf", Path("report.pdf").read_bytes()))] req = client.messages.create(data=data, files=files) ``` -------------------------------- ### Get domains with filters Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of domains with applied filters for pagination and limiting results. ```APIDOC ## Get domains with filters ### Description Retrieves a list of domains with applied filters, such as skipping a certain number of records and limiting the number of results returned. ### Method GET ### Endpoint /domains ### Parameters #### Query Parameters - **skip** (integer) - Optional - The number of records to skip. - **limit** (integer) - Optional - The maximum number of records to return. ### Response #### Success Response (200) - **domains** (list) - A list of domain objects matching the filters. ### Request Example ```python data = client.domainlist.get(filters={"skip": 0, "limit": 10}) print(data.json()) ``` ``` -------------------------------- ### Get Specific Mailgun User Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/endpoints.md Retrieve details for a specific account user by their user ID. ```python response = client.users.get(user_id="user_id") ``` -------------------------------- ### Send Message with Simple Client Initialization Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Send a message using a Mailgun client initialized directly with credentials. Suitable for simple scripts where connection cleanup is handled by garbage collection. ```python client = Client(auth=("api", "KEY")) client.messages.create(data={"to": "user@example.com"}) ``` -------------------------------- ### Send Email with Advanced Parameters Source: https://github.com/mailgun/mailgun-python/blob/main/README.md This example shows how to send an email with advanced features like tags, test mode, send time optimization, and custom variables. The SDK maps kwargs directly to the payload. ```python data = { "from": "Excited User ", "to": ["recipient1@example.com", "recipient2@example.com"], "subject": "Advanced Mailgun Features", "text": "Testing out tags, custom variables, and testmode!", "o:tag": ["newsletter", "python-sdk"], # Multiple tags "o:testmode": "yes", # Validates payload without actually sending "o:deliverytime-optimize-period": "24h", # Send Time Optimization "v:my-custom-id": "USER-12345", # Custom user-defined variable } req = client.messages.create(data=data) ``` -------------------------------- ### Get Domain Connections Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves connection information for a specific domain. The domain variable must be defined. ```python def get_connections() -> None: """ GET /domains//connection :return: """ request = client.domains_connection.get(domain=domain) print(request.json()) ``` -------------------------------- ### Get List of Domains Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of all domains associated with your Mailgun account. The result is printed as JSON. ```python data = client.domainlist.get() print(data.json()) ``` -------------------------------- ### Synchronous Client Initialization Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/README.md Initializes the synchronous Mailgun client using API key authentication. It's recommended to use the client as a context manager for proper resource handling. ```python from mailgun.client import Client import os auth = ("api", os.environ["MAILGUN_API_KEY"]) client = Client(auth=auth) # Best practice: use context manager with Client(auth=auth) as client: response = client.messages.create(data={...}) ``` -------------------------------- ### Using Mailgun Client with Context Manager Source: https://github.com/mailgun/mailgun-python/blob/main/_autodocs/api-reference-security.md Demonstrates the correct way to use the Mailgun `Client` with a context manager (`with` statement) to ensure credentials are automatically cleared from memory upon exiting the block. ```python from mailgun.client import Client # CORRECT: Credentials cleared on exit with Client(auth=("api", "key")) as client: response = client.messages.create(data={...}) # Auth is None, session closed # WRONG: Credentials remain in memory client = Client(auth=("api", "key")) response = client.messages.create(data={...}) # Credentials still in memory ``` -------------------------------- ### Get account tags Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves a list of account tags, sorted by last seen time, with pagination support. ```APIDOC ## Get account tags ### Description Retrieves a list of account tags, sorted by last seen time, with pagination support. ### Method POST ### Endpoint /v1/analytics/tags ### Parameters #### Query Parameters None #### Request Body - **pagination** (object) - Optional - Pagination settings, including sort order and limit. ### Request Example ```json { "pagination": {"sort": "lastseen:desc", "limit": 10} } ``` ### Response #### Success Response (200) - **tags** (array) - A list of account tags. #### Response Example ```json { "tags": [ ... ] } ``` ``` -------------------------------- ### Sync vs Async Client Method Calls Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Illustrates the identical method signatures between the synchronous and asynchronous clients. Note the use of 'await' for async calls. ```python # Sync version client = Client(auth=auth) result = client.domainlist.get() # Async version client = AsyncClient(auth=auth) result = await client.domainlist.get() ``` -------------------------------- ### Get Domain Tracking Settings Source: https://github.com/mailgun/mailgun-python/blob/main/README.md Retrieves the tracking settings for a specific domain. The domain variable must be defined. ```python def get_tracking() -> None: """ GET /domains//tracking :return: """ request = client.domains_tracking.get(domain=domain) print(request.json()) ```