---
title: Mailgun API Implementation Guide for Product Teams | SendHQ
description: Implement Mailgun with verified domains, scoped credentials, durable send jobs, authenticated webhooks, precise events, and suppression-aware workflows.
canonical: https://sendhq.cc/guides/mail-gun-api
last-updated: 2026-08-24
---
# How should a product team implement the Mailgun API safely?

Implement the Mailgun API behind an authorized server worker. Verify the exact sending domain, use the narrowest API credential available, create a durable internal send job, and submit multipart form data to the domain-scoped Messages endpoint. Store Mailgun’s returned message identifier, authenticate webhook requests before processing them, deduplicate events, and enforce bounces, complaints, and unsubscribes at send time. Keep API acceptance, Mailgun processing, receiving-server delivery, and inbox placement as separate states.

## Define a narrow product operation before calling Mailgun

Start with an approved product event such as account verification, a receipt, a security alert, or a notification the recipient requested. Put Mailgun behind a trusted application service or queue worker rather than exposing a provider credential or arbitrary message form to browsers and mobile clients. Authorize the caller, tenant, sender identity, recipient, message class, and template before creating provider fields. Persist an internal outbound record with a stable event key, tenant, template revision, approved addresses, and initial state. This record is the system of decision; Mailgun is the transport dependency. Separating business intent from provider payloads makes retries and audits safer and keeps a later provider migration possible. Transactional and consent-dependent traffic should remain distinct in the data model so recipient preferences, suppression rules, and reputation incidents do not become an informal template convention.

## Verify the exact sending domain and DNS records

Add a domain controlled by the organization and publish the DNS records Mailgun currently provides for verification, authentication, tracking, and receiving features actually selected. Review existing SPF and DMARC records before changing DNS. Do not create a second SPF record at one hostname or replace an organizational DMARC policy without its owner. Verify the actual From and signing identity used by the workload, not merely an adjacent parent domain. Use a purpose-specific subdomain when ownership, traffic separation, or migration warrants it. After Mailgun reports verification, inspect a controlled received message for the visible From address, DKIM signing domain, return path, authentication results, and reply behavior. Provider verification is evidence that its setup check passed. It does not prove recipient consent, destination acceptance, sender reputation, or inbox placement. Retain DNS change history and rollback instructions outside the provider dashboard.

## Use scoped credentials and the correct regional endpoint

Mailgun documents HTTP Basic authentication for its APIs, with API credentials that differ by authority and purpose. A sending worker should receive only the credential needed for the approved domain and operation. Keep primary account keys, domain sending keys, webhook signing material, and lower-environment credentials separate. Store secrets directly in a managed secret store and expose them only to the server process that needs them. Never put credentials in client code, source control, URLs, logs, analytics, templates, tickets, or prompts. Select the documented API base URL for the account’s region rather than assuming every domain uses the same host. Rehearse rotation by creating an equivalently scoped replacement, updating the worker, verifying controlled traffic and events, then revoking the old credential. Alert on unexpected authentication and authorization failures because they can signal revocation, incorrect region, scope drift, or exposure.

## Build one durable Messages API request

Mailgun’s domain-scoped Messages endpoint accepts multipart form fields for sender, recipients, subject, text or HTML content, and documented options such as templates, attachments, headers, tags, recipient variables, tracking, and scheduled delivery. Expose only the subset the product needs. Validate address syntax and tenant ownership, bound recipient and attachment counts, reject newline injection, and render approved templates with typed variables. Do not place secrets or unnecessary personal data in tags, custom variables, or headers because provider events and activity views can surface metadata separately from message content. Submit from the claimed internal job and store Mailgun’s returned message identifier with the exact attempt. Keep provider-specific option names inside one adapter. Business code should receive a narrow accepted, rejected, or uncertain result rather than learn every Mailgun field and error shape.

## Design retries around acceptance and ambiguity

Classify responses before retrying. Fix malformed fields, unauthorized domains, invalid credentials, permission failures, and permanent policy errors rather than replaying them. Retry eligible transport failures, provider server errors, and rate-limited requests with exponential backoff, jitter, a finite attempt count, and queue-age limits. Mailgun’s accepted API response means the provider accepted the submission request for processing; it does not prove the destination server accepted the message. A client timeout is ambiguous because Mailgun may have accepted the request even though the worker missed the response. Hold that job in an unknown state, search for the stored correlation data or later events, and apply a deliberate reconciliation rule before resending. Mailgun transport does not remove the need for a stable application event key, single-worker claim, attempt history, and duplicate-risk controls. Alert on repeated failures by credential, domain, template, tenant, and destination provider.

## Authenticate webhook requests before parsing

Configure an HTTPS webhook endpoint and preserve the exact fields used by Mailgun’s signing procedure. Mailgun documents a timestamp, token, and signature derived with the webhook signing key. Validate the signature using a constant-time comparison and reject timestamps outside the application’s freshness window before accepting the event. Track tokens or event identifiers as needed for replay resistance. Keep the webhook signing key separate from sending credentials and rotate it through a tested process. Apply request-size limits and do not trust URLs, recipients, tags, or event fields merely because the body parses. After authentication, durably store or enqueue the event before returning success. This prevents a process crash from discarding delivery evidence. Webhook verification proves origin and integrity under the configured secret; it does not prove the business event belongs to the expected tenant until the application correlates domain and provider message identifiers.

## Handle webhook retries and duplicate events idempotently

Mailgun documents webhook retry behavior when an endpoint does not return an expected success response. The receiver must assume delayed and repeated delivery. Deduplicate on a stable provider event identifier when present, or on a conservative composite that cannot merge different recipients or event types. Preserve the original occurrence time and processing time separately. Make state transitions monotonic so an older accepted or delivered observation cannot erase a later permanent failure, complaint, or unsubscribe merely because retries arrive out of order. Return success only after durable capture, but keep expensive business processing asynchronous so the endpoint remains reliable. Monitor signature failures, response latency, retry volume, event lag, and dead-letter records. Retain raw provider payloads only as long as operational and policy needs justify, with restricted access and address minimization. A webhook is an evidence feed, not permission to expose recipient history across tenants.

## Model Mailgun events without overstating delivery

Mailgun documents event types for accepted, delivered, temporary and permanent failure, opened, clicked, unsubscribed, complained, stored, and related processing outcomes. Map those names to an internal model while retaining the provider event type, message identifier, recipient scope, timestamp, severity, and available SMTP response. Accepted describes Mailgun intake or queue progress. Delivered describes the documented delivery observation, commonly destination-server acceptance, but does not reveal the final mailbox folder. Opens and clicks are engagement instrumentation, not transport proof, and privacy technology can affect them. Temporary failures can justify bounded retry inside the transport system; permanent failures, complaints, and unsubscribes must update recipient-safety state before any later application job is submitted. Keep the event ledger append-only and derive a user-facing status through explicit rules so support can distinguish evidence from interpretation.

## Enforce failures, complaints, and unsubscribes at send time

Mailgun documents tracking for delivery failures, spam complaints, and unsubscribes. Ingest those signals into a product-owned recipient-safety model with tenant, address, message class, source event, reason, and effective time. Check that state immediately before each send, not only when a campaign list is imported. A permanent bounce or complaint should stop unsafe retries for the applicable scope. Unsubscribe handling must respect message class and current receiver or legal requirements; it should not be bypassed routinely through provider options. Protect any manual removal with strong authorization, a visible reason, and audit history. Provider suppression data is valuable operational evidence but is not a complete consent ledger. Preserve consent source, preferences, product-critical policy decisions, and prior provider history separately so a migration does not discard recipient protection. Test suppression propagation, duplicate complaints, delayed bounces, and exceptional reactivation with controlled identities.

## Consider SendHQ as a Mailgun alternative

SendHQ offers transactional and permission-based marketing email with verified-domain sending, inbound email, delivery events, and suppressions. Review its public API documentation and test authentication, payloads, errors, identifiers, events, domains, and recipient-safety workflows before migrating.

## Frequently asked questions

**What endpoint sends email through the Mailgun API?**

Mailgun documents a domain-scoped \`POST /v3/{domain}/messages\` endpoint using multipart form data and HTTP Basic authentication. Call it only from authorized server-side code.

**Should a Mailgun API key be placed in browser code?**

No. Store the narrowest suitable credential in a server-side secret manager. Keep production, lower environments, account administration, domain sending, and webhook signing authority separate.

**Does Mailgun API acceptance mean an email was delivered?**

No. It means Mailgun accepted the submission for processing. Authenticated events can later report destination-server delivery or failure, while inbox placement remains a separate receiver-side outcome.

**How should Mailgun webhooks be authenticated?**

Validate Mailgun’s documented timestamp, token, and signature with the webhook signing key before processing. Apply freshness and replay controls, then durably capture the event before acknowledging it.

**Should every Mailgun API failure be retried?**

No. Correct validation, authentication, domain, permission, and permanent policy errors. Use bounded backoff for eligible transient failures and reconcile ambiguous timeouts before resending.

**Can SendHQ replace Mailgun?**

Possibly. SendHQ offers transactional and permission-based marketing email with verified-domain sending, inbound email, delivery events, and suppressions. Review its public API documentation and test your integration before migrating.

## Sources

- [Mailgun Messages API](https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/messages/post-v3--domain-name--messages) — Mailgun
- [Mailgun API Authentication](https://documentation.mailgun.com/docs/mailgun/api-reference/mg-auth) — Mailgun
- [Verify a Mailgun Domain](https://documentation.mailgun.com/docs/mailgun/user-manual/domains/domains-verify) — Mailgun
- [Mailgun Event Types](https://documentation.mailgun.com/docs/mailgun/user-manual/events/event-types) — Mailgun
- [Securing Mailgun Webhooks](https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/securing-webhooks) — Mailgun
- [Mailgun Webhook Retries](https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/webhook-retries) — Mailgun
- [Tracking Mailgun Delivery Failures](https://documentation.mailgun.com/docs/mailgun/user-manual/tracking-messages/tracking-failures) — Mailgun
- [Tracking Mailgun Spam Complaints](https://documentation.mailgun.com/docs/mailgun/user-manual/tracking-messages/tracking-spam-complaints) — Mailgun
- [Tracking Mailgun Unsubscribes](https://documentation.mailgun.com/docs/mailgun/user-manual/tracking-messages/tracking-unsubscribes) — Mailgun
- [RFC 5321: Simple Mail Transfer Protocol](https://www.rfc-editor.org/rfc/rfc5321.html) — RFC Editor
- [SendHQ OpenAPI Contract](https://sendhq.cc/openapi.json) — SendHQ

## Continue learning

- [Email API Implementation Guide for Product Teams](https://sendhq.cc/guides/email-api.md): Design a safe email API integration with verified domains, queued sends, stable identifiers, controlled retries, delivery events, suppression, and tenant isolation.
- [SendGrid API Implementation Guide for Product Teams](https://sendhq.cc/guides/sendgrid-api.md): Implement SendGrid with authenticated domains, scoped API keys, durable send records, verified event webhooks, and suppression-aware workflows.
- [Resend Email API Implementation Guide for Product Teams](https://sendhq.cc/guides/resend-email-api.md): Implement the Resend email API with verified domains, scoped keys, idempotent sends, signed webhooks, durable events, and honest delivery states.
- [How to Evaluate an SMTP Relay Service](https://sendhq.cc/guides/smtp-relay-service.md): Evaluate SMTP relay services by submission security, authentication, queues, retry behavior, limits, delivery events, suppression, isolation, and migration fit.
