Getting started overview

Integrating Mailgun involves several sequential steps, beginning with account creation and domain configuration, followed by API key retrieval and a test email send. Mailgun provides a RESTful API and client libraries (SDKs) to facilitate programmatic email sending, receiving, and management. The platform is designed for developers to integrate email functionalities directly into applications, supporting use cases such as transactional emails, email marketing, and inbound email processing.

This guide outlines the essential steps to get Mailgun operational, from initial setup to sending your first email via the API. The process focuses on establishing a verified sending environment and executing a basic API call.

Here is a quick reference table for the steps to get started with Mailgun:

Step What to Do Where
1. Create Account Register for a Mailgun account. Mailgun Pricing page
2. Add Domain Add a sending domain to your Mailgun account. Mailgun Control Panel > Sending > Domains
3. Verify Domain Configure DNS records (MX, TXT, CNAME) with your domain registrar. Mailgun Control Panel > Sending > Domains (specific domain details)
4. Get API Key Retrieve your private API key. Mailgun Control Panel > Settings > API Keys
5. Send Test Email Use cURL or an SDK to send your first email. Command Line / Integrated Development Environment (IDE)

Create an account and get keys

To begin using Mailgun, an account is required. Mailgun offers a free tier allowing 1,000 emails per month for the first three months, suitable for testing and development. Paid plans, such as the Foundation tier, start at $35/month for 50,000 emails.

Account Registration

  1. Navigate to the Mailgun website.
  2. Select your desired plan (e.g., the free trial) and complete the registration form, providing necessary contact and billing information.
  3. Verify your email address and phone number as prompted. This ensures compliance and helps prevent misuse.

Adding and Verifying a Sending Domain

A verified sending domain is essential for sending emails through Mailgun. This step involves configuring DNS records with your domain registrar to prove domain ownership and establish email authenticity. Proper DNS setup, including MX, TXT (SPF and DKIM), and CNAME records, helps improve email deliverability and reduces the likelihood of emails being flagged as spam. The Domain Name System (DNS) is a hierarchical and distributed naming system for computers, services, or any resource connected to the Internet or a private network, as defined by the IETF RFC 1034.

  1. Add Your Domain: In the Mailgun Control Panel, navigate to 'Sending' > 'Domains' and click 'Add New Domain'. Enter your domain name (e.g., yourcompany.com).
  2. Configure DNS Records: Mailgun will provide specific MX, TXT (SPF and DKIM), and CNAME records. You must add these records to your domain's DNS settings via your domain registrar's control panel.
  3. Verify DNS: After adding the records, return to the Mailgun Control Panel. Mailgun will periodically check for the DNS updates. Verification can take up to 48 hours, though it often completes within minutes or hours. The domain status will change to 'Active' once verified.

Retrieving API Keys

Mailgun uses API keys for authentication. There are two types: a Public API Key (primarily for client-side validation) and a Private API Key (for server-side operations, including sending emails). For sending emails, the Private API Key is required.

  1. In the Mailgun Control Panel, go to 'Settings' > 'API Keys'.
  2. Locate your Private API Key. It will typically start with key-.
  3. Copy this key. Ensure it is stored securely and is not exposed in client-side code or public repositories.

Your first request

After setting up your domain and obtaining your API key, you can send your first email. This example uses cURL, a common command-line tool, to demonstrate the API call. Mailgun also provides SDKs for various languages, including Python, Ruby, PHP, Node.js, and Java, for more complex integrations.

Prerequisites

  • A verified sending domain in your Mailgun account.
  • Your Private API Key.
  • A recipient email address for testing.

Sending an email with cURL

The following cURL command sends a simple text email. Replace the placeholders with your actual domain, API key, and email addresses.


curl -s --user 'api:YOUR_PRIVATE_API_KEY' \
    https://api.mailgun.net/v3/YOUR_VERIFIED_DOMAIN/messages \
    -F from='Excited User <mail@YOUR_VERIFIED_DOMAIN>' \
    -F to='[email protected]' \
    -F subject='Hello From Mailgun!' \
    -F text='Congratulations, you have sent an email with Mailgun.'
  • YOUR_PRIVATE_API_KEY: Replace this with the Private API Key copied from your Mailgun Control Panel.
  • YOUR_VERIFIED_DOMAIN: Replace this with the domain you added and verified in Mailgun (e.g., yourcompany.com).
  • [email protected]: Replace this with the email address where you want to receive the test email.

Upon successful execution, the API will return a JSON response indicating the message ID and a success message. Check the recipient's inbox for the test email. You can also view logs in the Mailgun Control Panel under 'Sending' > 'Logs' to confirm delivery status.

Sending an email with Python SDK

For a Python implementation, ensure you have the Mailgun SDK installed:


pip install mailgun-sdk

Then, use the following Python code:


from mailgun import Mailgun

mg = Mailgun(api_key='YOUR_PRIVATE_API_KEY', domain='YOUR_VERIFIED_DOMAIN')

message = {
    'from': 'Excited User <mail@YOUR_VERIFIED_DOMAIN>',
    'to': '[email protected]',
    'subject': 'Hello From Mailgun! (Python)',
    'text': 'Congratulations, you have sent an email with Mailgun using Python.'
}

response = mg.send_message(message)
print(response)

For other languages, refer to the Mailgun SDK documentation for specific examples.

Common next steps

After successfully sending your first email, consider these common next steps to enhance your Mailgun integration:

  • Webhooks: Configure webhooks to receive real-time notifications about email events such as delivered, opened, clicked, or bounced emails. This enables tracking and automation within your application. More details are available in the Mailgun Webhooks documentation.
  • Templates: Utilize email templates for consistent branding and easier management of transactional or marketing emails. Mailgun allows you to create and manage templates directly or integrate with external template engines.
  • Email Validation: Integrate Mailgun's email validation API to reduce bounce rates and improve deliverability by verifying email addresses before sending. This service checks for syntax, domain validity, and disposable email addresses.
  • Inbound Routing: Set up inbound routes to process incoming emails, allowing your application to receive and act upon replies or other incoming mail. This is useful for building features like support ticket systems or comment-by-email functionalities. The Mailgun Inbound Routing guide provides configuration details.
  • Dedicated IPs: For high-volume senders, consider using a dedicated IP address to build and maintain your sending reputation independently. This can be crucial for maximizing deliverability.
  • Advanced Analytics: Explore Mailgun's analytics dashboard and API to gain insights into your email performance, including open rates, click-through rates, and bounce rates.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting steps:

  • API Key Error: Double-check that you are using your Private API Key (starts with key-) and not the Public API Key. Ensure there are no typos or extra spaces.
  • Domain Not Verified: Verify that your sending domain is active in the Mailgun Control Panel. If the DNS records have been recently updated, it might take some time for them to propagate globally. Use a DNS lookup tool to confirm your MX, SPF, and DKIM records are correctly published.
  • Incorrect Endpoint: Ensure the API endpoint matches your Mailgun region. The default is api.mailgun.net for the US, but it may differ for EU accounts (e.g., api.eu.mailgun.net). Check your Mailgun account settings for the correct region-specific endpoint. The Mailgun API Reference specifies regional endpoints.
  • From Address Mismatch: The 'From' address in your email request must use your verified sending domain (e.g., mail@YOUR_VERIFIED_DOMAIN). Sending from an unverified domain will result in errors.
  • Firewall/Network Issues: If you are working behind a corporate firewall, ensure that outgoing connections to api.mailgun.net (or your regional equivalent) on HTTPS port 443 are allowed.
  • Mailgun Logs: Always check the 'Logs' section in your Mailgun Control Panel. It provides detailed error messages and delivery statuses, which can pinpoint the exact issue.
  • SDK Specific Issues: If using an SDK, ensure it is installed correctly and you are following the syntax for your chosen language. Refer to the Mailgun SDK documentation for language-specific guidance.
  • Rate Limiting: While unlikely for a first call, be aware that excessive requests in a short period can trigger rate limiting. Check the Mailgun API Rate Limits documentation for details.