Skip to main content
RapidDev - Software Development Agency
retool-integrationsREST API Resource

How to Integrate Retool with Mailgun

Connect Retool to Mailgun by creating a REST API Resource using Mailgun's API key with Basic Auth ('api' as the username, your API key as the password). Set the base URL to https://api.mailgun.net/v3 or the EU endpoint https://api.eu.mailgun.net/v3. Once configured, query Mailgun's Events API for delivery tracking, manage suppressions, monitor bounces, and build email operations dashboards.

What you'll learn

  • How to find your Mailgun API key and configure the correct regional base URL
  • How to configure Mailgun's Basic Auth ('api' username + API key) in a Retool REST API Resource
  • How to query Mailgun's Events API for real-time delivery tracking and bounce analysis
  • How to build an email delivery monitoring dashboard with suppression management
  • How to create alerting workflows for delivery failures using Retool Workflows
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate15 min read20 minutesCommunicationLast updated April 2026RapidDev Engineering Team
TL;DR

Connect Retool to Mailgun by creating a REST API Resource using Mailgun's API key with Basic Auth ('api' as the username, your API key as the password). Set the base URL to https://api.mailgun.net/v3 or the EU endpoint https://api.eu.mailgun.net/v3. Once configured, query Mailgun's Events API for delivery tracking, manage suppressions, monitor bounces, and build email operations dashboards.

Quick facts about this guide
FactValue
ToolMailgun
CategoryCommunication
MethodREST API Resource
DifficultyIntermediate
Time required20 minutes
Last updatedApril 2026

Build a Mailgun Email Delivery Monitoring Dashboard in Retool

Mailgun's native activity log in the dashboard provides event tracking, but operations and engineering teams often need custom views: a real-time bounce dashboard that alerts when delivery rates drop, a suppression management panel for operations teams to clear or investigate blocked recipients, or a multi-domain delivery health report that crosses the boundaries of Mailgun's native domain-by-domain view. Retool enables all of these patterns through Mailgun's comprehensive REST API.

Mailgun's Events API is its most powerful feature — it provides a full audit trail of every email event (accepted, delivered, failed, bounced, complained, unsubscribed, opened, clicked) with filtering by recipient, domain, timestamp, and event type. This granularity makes Mailgun ideal for building detailed delivery monitoring dashboards that can surface issues like sudden bounce rate spikes or specific ISP blocking patterns.

The Mailgun API uses Basic Auth with a fixed username of 'api' (literally the string 'api') and your private API key as the password. This differs from Mailchimp's 'anystring' pattern — the username must be exactly 'api'. All requests must target the correct regional endpoint: US-hosted accounts use api.mailgun.net and EU-hosted accounts use api.eu.mailgun.net. Using the wrong endpoint results in authentication errors even with correct credentials.

Integration method

REST API Resource

Mailgun connects to Retool via a REST API Resource using Basic Auth with 'api' as the fixed username and your Mailgun API key as the password. The base URL includes your account's regional endpoint (US or EU). All requests are proxied server-side through Retool, eliminating CORS issues and keeping your API key off the browser. Mailgun's Events API provides granular delivery event tracking that powers email operations dashboards in Retool.

Prerequisites

  • A Mailgun account with at least one verified sending domain and email history to query
  • A Mailgun Private API Key (found in Mailgun Dashboard → Settings → API Keys — use the Private API Key, not the Public Validation Key)
  • Your sending domain name(s) in Mailgun (used in API endpoint paths)
  • Knowledge of whether your Mailgun account is on the US (api.mailgun.net) or EU (api.eu.mailgun.net) endpoint
  • A Retool account with permission to create Resources

Step-by-step guide

1

Find your Mailgun API key and determine your region

Log into your Mailgun Dashboard at app.mailgun.com. Navigate to Settings (gear icon in the left sidebar) → API Keys. You will see two types of keys: 1. Private API Key — starts with key-XXXXXXXX. This is the key to use for Retool. It has full access to send emails, access logs, and manage suppressions. 2. HTTP Webhook Signing Key — used for verifying webhook payloads. Do NOT use this for API authentication. 3. Public Validation Key — used for client-side email validation. Do NOT use this for backend API access. Copy the Private API Key value. Store it immediately in Retool Settings → Configuration Variables as MAILGUN_API_KEY marked as secret. Next, determine your Mailgun region. If you signed up through the standard mailgun.com signup and your account dashboard URL is app.mailgun.com, your region is US and you use: https://api.mailgun.net/v3 If you signed up specifically for the EU region (your dashboard might show eu.mailgun.com), use: https://api.eu.mailgun.net/v3 Also note your primary sending domain name (e.g., mg.yourcompany.com or mail.yourcompany.com) — this is required in many Mailgun API endpoint paths. Find it in Mailgun Dashboard → Sending → Domains.

Pro tip: Mailgun's Private API Key is a 36-character hex string prefixed with 'key-'. If your key doesn't start with 'key-', you may have copied the wrong key type — double-check you're using the Private API Key, not the HTTP Signing Key.

Expected result: You have your Mailgun Private API Key stored in Retool Configuration Variables, you know your region (US or EU), and you have your sending domain name ready.

2

Create the Mailgun REST API Resource in Retool

In Retool, navigate to the Resources tab and click Add Resource. Select REST API. Name: Mailgun API Base URL: https://api.mailgun.net/v3 (for US region) or https://api.eu.mailgun.net/v3 (for EU region) Authentication: Select Basic Auth. - Username: api (literally the word 'api' — this is a fixed value, not your email address) - Password: {{ retoolContext.configVars.MAILGUN_API_KEY }} (or paste your key directly) This is different from Mailchimp's 'anystring' — Mailgun specifically requires 'api' as the username. Using any other username (even your email address) causes authentication to fail. Headers: - Key: Content-Type | Value: application/x-www-form-urlencoded (for POST requests like sending email — use application/json for GET queries) Click Create Resource. Test the connection by creating a query with method GET and path /domains — this should return a JSON object with a list of your verified Mailgun domains. If it returns a 401 Unauthorized, double-check that Username is exactly 'api' and the Password is your Private API Key (not the validation key). Note: Many Mailgun endpoints include the domain name in the path — for example /YOUR_DOMAIN/events. You'll reference your domain in query paths using a Retool variable, not in the base URL.

Pro tip: Create a Select component in your Retool app populated with your domain list from the /domains endpoint. Use the selected domain in query paths so you can switch between multiple sending domains without editing individual queries.

Expected result: The Mailgun API resource is created and a test GET /domains returns your verified Mailgun sending domains in JSON format.

3

Query the Events API for delivery tracking

Mailgun's Events API is the core of delivery monitoring. Create a query named getEvents. Set the method to GET and path to /{{ select_domain.value }}/events. Key query parameters: - begin: {{ new Date(dateRange.start).toUTCString() }} — start of event window (RFC 2822 format or Unix timestamp) - end: {{ new Date(dateRange.end).toUTCString() }} — end of event window - ascending: no (newest events first) - limit: 100 — events per page (max 300) - event: {{ select_event_type.value || '' }} — filter by event type: 'delivered', 'bounced', 'failed', 'complained', 'unsubscribed', 'opened', 'clicked' - recipient: {{ textInput_email.value || '' }} — filter by recipient address - subject: {{ textInput_subject.value || '' }} — filter by subject line The response includes an items array of event objects and a paging object with cursor URLs for pagination. Each event object contains event type, timestamp, message (with headers including subject and message-id), recipient, and delivery-status (for failed/bounced events with error codes and descriptions). Create a transformer to flatten the nested message headers and delivery status into displayable columns. Extract the Subject and From headers from the deeply nested message.headers object.

transformer_events.js
1// Transformer for Mailgun events
2const events = data.items || [];
3return events.map(e => {
4 const headers = e.message?.headers || {};
5 const deliveryStatus = e['delivery-status'] || {};
6 return {
7 event: e.event,
8 timestamp: e.timestamp ? new Date(e.timestamp * 1000).toLocaleString() : '',
9 recipient: e.recipient || '',
10 sender: headers['from'] || '',
11 subject: headers['subject'] || '(no subject)',
12 message_id: headers['message-id'] || '',
13 status_code: deliveryStatus.code || '',
14 status_message: deliveryStatus.message || '',
15 error_description: deliveryStatus.description || '',
16 geolocation: e.geolocation ? `${e.geolocation.city || ''}, ${e.geolocation.country || ''}`.replace(/^,\s*|,\s*$/g, '') : '',
17 user_agent: e['user-agent'] || ''
18 };
19});

Pro tip: Mailgun stores events for 30 days on the Flex plan and longer on higher plans. For delivery audit trails that need to go beyond the retention window, export events daily to a database using a Retool Workflow.

Expected result: The Events API query returns email delivery events with subject lines, recipient addresses, delivery status codes, and error descriptions in a filterable Retool Table.

4

Build suppression management queries

Mailgun tracks three types of suppressions that prevent future delivery: bounces (permanent delivery failures), complaints (spam reports), and unsubscribes (opt-outs). Build separate queries for each type and combine them into a tabbed Retool UI. getBounces: GET /{{ select_domain.value }}/bounces - limit: 100 - Response: array of {address, code, error, created_at} getComplaints: GET /{{ select_domain.value }}/complaints - limit: 100 - Response: array of {address, created_at} getUnsubscribes: GET /{{ select_domain.value }}/unsubscribes - limit: 100 - tag: optional tag filter - Response: array of {address, tags, created_at} To remove a suppression (re-enable delivery to an address), create write queries: - deleteBounce: DELETE /{{ select_domain.value }}/bounces/{{ table_bounces.selectedRow?.data?.address }} - deleteComplaint: DELETE /{{ select_domain.value }}/complaints/{{ table_complaints.selectedRow?.data?.address }} - deleteUnsubscribe: DELETE /{{ select_domain.value }}/unsubscribes/{{ encodeURIComponent(table_unsubscribes.selectedRow?.data?.address || '') }} Set all DELETE queries to Manual trigger only. Wire them to a 'Remove Suppression' button with a confirmation modal. On Success, trigger the appropriate GET query to refresh the list. For customer support use cases, add a 'Search Any Suppression' query that searches across all three suppression types for a given email address using three parallel queries combined in a JavaScript query.

suppression_search.js
1// Combined suppression search across all types
2const email = textInput_search_email.value;
3if (!email) return [];
4
5// Run all three lookups in parallel
6const [bounces, complaints, unsubscribes] = await Promise.all([
7 getBounces.trigger({ additionalScope: { search_email: email } }),
8 getComplaints.trigger({ additionalScope: { search_email: email } }),
9 getUnsubscribes.trigger({ additionalScope: { search_email: email } })
10]);
11
12const results = [];
13(bounces?.items || []).forEach(b => results.push({ ...b, suppression_type: 'Bounce' }));
14(complaints?.items || []).forEach(c => results.push({ ...c, suppression_type: 'Complaint' }));
15(unsubscribes?.items || []).forEach(u => results.push({ ...u, suppression_type: 'Unsubscribe' }));
16
17return results;

Pro tip: Email addresses in Mailgun suppression DELETE endpoints must be URL-encoded. Use encodeURIComponent() in the query path template for addresses that may contain + characters (common in Gmail aliases like user+tag@gmail.com).

Expected result: The suppression management panel shows separate tabs for bounces, complaints, and unsubscribes, with a search field for finding specific addresses and a button to remove suppressions.

5

Build delivery rate analytics and alerting workflows

Create aggregate delivery analytics using the Events API with event type filtering. To compute delivery rates, query total accepted events and compare with delivered events: For domain statistics, use Mailgun's Stats API: GET /{{ select_domain.value }}/stats/total with: - event: delivered,bounced,failed,complained (comma-separated) - start: {{ moment(dateRange.start).format('YYYY-MM-DD') }} - duration: {{ diffDays }}d — number of days to aggregate - resolution: day — aggregate by day (or 'hour' for intraday trends) The stats endpoint returns pre-aggregated counts per time bucket — much more efficient than fetching all individual events for rate calculations. Transform the stats response to compute daily delivery rate: delivered / (delivered + failed + bounced). Display this in a Line Chart component. For alerting: create a Retool Workflow that runs every hour and calls the stats endpoint for the last hour. If the bounce rate exceeds a threshold (e.g., 5%), trigger a Slack notification via the Slack Resource. Store the threshold as a Retool Configuration Variable so it can be adjusted without editing the Workflow. For complex multi-domain delivery monitoring with automated alerting, RapidDev's team can help design the Workflow architecture and notification routing logic.

transformer_stats_chart.js
1// Transformer for delivery rate trend chart
2const stats = data.stats || [];
3return {
4 dates: stats.map(s => new Date(s.time).toLocaleDateString()),
5 delivered: stats.map(s => s.delivered?.total || 0),
6 bounced: stats.map(s => s.bounced?.total || 0),
7 failed: stats.map(s => s.failed?.total || 0),
8 delivery_rate: stats.map(s => {
9 const delivered = s.delivered?.total || 0;
10 const total = delivered + (s.bounced?.total || 0) + (s.failed?.total || 0);
11 return total > 0 ? parseFloat(((delivered / total) * 100).toFixed(1)) : null;
12 })
13};

Pro tip: Use the Stats API (/stats/total) for dashboard charts rather than the Events API — stats are pre-aggregated and return in a single request. Reserve the Events API for drill-down investigation of specific delivery failures.

Expected result: The analytics panel shows delivery rate trend charts and bounce rate statistics, with a Retool Workflow configured to send Slack alerts when bounce rates exceed the configured threshold.

Common use cases

Build an email delivery health monitoring dashboard

Create a Retool dashboard showing email delivery metrics across your Mailgun domains: delivery rates, bounce rates, complaint rates, and failed delivery counts. Engineering and ops teams can see real-time delivery health, identify sudden bounce rate spikes (often indicating list quality issues or ISP blocking), and drill into specific recipient domains to investigate delivery problems.

Retool Prompt

Build a Retool email delivery dashboard for Mailgun. Show a Table of sending domains with today's delivered count, bounced count, complained count, and delivery rate. Add a Line chart showing delivery rate trend over the last 7 days. Include stat components for total sent, total delivered, overall bounce rate, and complaint rate. Add a filter for date range and sending domain.

Copy this prompt to try it in Retool

Build a suppression management panel

Create a Retool tool for managing Mailgun suppressions: view all bounces, complaints, and unsubscribes, search for specific recipient addresses, and delete suppressions for recipients who should be re-enabled. This is faster than using Mailgun's native suppression management UI for operations teams handling customer support requests about email delivery.

Retool Prompt

Build a Retool Mailgun suppression manager. Show tabs for Bounces, Complaints, and Unsubscribes. Each tab shows a searchable Table of suppressed addresses with the suppression date and reason. Add a Delete Suppression button for selected rows with a confirmation modal. Include a search input to find a specific email address across all suppression types.

Copy this prompt to try it in Retool

Build a transactional email audit trail

Create a Retool panel for customer support teams that lets them look up email delivery history for any recipient address: has the welcome email been delivered, when was the last password reset sent, which promotional emails were opened vs bounced. This gives support teams the visibility to resolve 'I never received your email' tickets without needing Mailgun admin access.

Retool Prompt

Build a Retool email audit tool. Include a search input for recipient email address. Show all Mailgun events for that address in a Table: event type, timestamp, subject line, message ID, and delivery result. Add event type filters (delivered, bounced, opened). Display a summary showing last successful delivery date and total events in the last 30 days.

Copy this prompt to try it in Retool

Troubleshooting

401 Unauthorized despite correct API key

Cause: Mailgun's Basic Auth requires 'api' as the username — literally the string 'api', not your email address or 'apikey' or 'anystring'. Using any other username causes authentication to fail, even with the correct API key as the password.

Solution: In the Retool resource Basic Auth settings, confirm that Username is exactly 'api' (lowercase, no quotes, no spaces) and Password is your Mailgun Private API Key. Do not use your email address or 'apikey' as the username. If the key value looks correct, double-check you're using the Private API Key (starting with 'key-') rather than the HTTP Webhook Signing Key.

API calls succeed but return no events despite known email activity

Cause: The base URL may be pointed at the wrong regional endpoint. EU-hosted Mailgun accounts must use api.eu.mailgun.net — using api.mailgun.net with EU credentials authenticates successfully (your credentials work on both) but returns results from the wrong region's data store, showing no events.

Solution: Check your Mailgun account region in the dashboard. If your domain's MX records point to EU servers, update the Retool resource base URL to https://api.eu.mailgun.net/v3. Test with GET /domains — if it returns your domains correctly, you're on the right endpoint for your account.

Events API returns an empty items array for a date range that should have activity

Cause: The begin and end date parameters are not formatted correctly. Mailgun accepts RFC 2822 date strings or Unix timestamps for these parameters. Passing ISO 8601 format (YYYY-MM-DDTHH:mm:ssZ) may not be parsed correctly by all Mailgun API versions.

Solution: Use JavaScript's toUTCString() to format dates for Mailgun's begin/end parameters: {{ new Date(dateRange.start).toUTCString() }}. Alternatively, pass a Unix timestamp in seconds: {{ Math.floor(new Date(dateRange.start).getTime() / 1000) }}. Test with a simple date 24 hours ago to confirm events are returned before adding more complex filters.

typescript
1// Unix timestamp format for Mailgun date parameters:
2// begin: {{ Math.floor(new Date(dateRange.start).getTime() / 1000) }}
3// end: {{ Math.floor(new Date(dateRange.end).getTime() / 1000) }}

DELETE suppression request returns 404 Not Found for a known bounced address

Cause: Email addresses with special characters (particularly + in Gmail aliases like user+tag@gmail.com) must be URL-encoded in the DELETE endpoint path. An unencoded + becomes a space in the URL, causing a 404.

Solution: Wrap the email address in encodeURIComponent() in the query path: /{{ select_domain.value }}/bounces/{{ encodeURIComponent(table_bounces.selectedRow?.data?.address || '') }}. This correctly encodes + to %2B and other special characters, allowing Mailgun to match the exact email address.

typescript
1/{{ select_domain.value }}/bounces/{{ encodeURIComponent(table_bounces.selectedRow?.data?.address || '') }}

Best practices

  • Store the Mailgun Private API Key in Retool Configuration Variables (Settings → Configuration Variables) marked as secret — never paste it directly into query paths or share it with non-admin Retool users.
  • Always use the correct regional base URL — EU-hosted Mailgun accounts must use api.eu.mailgun.net. Using the wrong region returns empty data or authentication confusion even when credentials are valid.
  • Use the Stats API (/stats/total) for charts and aggregate metrics, and reserve the Events API (/events) for drill-down investigation — stats are pre-aggregated and much faster to query for dashboards showing daily trends.
  • Set up daily event exports to a database using Retool Workflows — Mailgun retains events for only 30 days on the Flex plan (5 days on free plans). For audit trails and historical analysis, persist events to PostgreSQL or another database.
  • URL-encode email addresses in DELETE endpoint paths using encodeURIComponent() — addresses with + characters (common in Gmail aliases) will cause 404 errors if not encoded.
  • Create a dedicated Mailgun API key for Retool with read-only permissions where possible — if Mailgun supports API key scoping in your plan tier, use a key that cannot send email to minimize risk if the key is ever exposed.
  • Cache the /domains endpoint response for at least 10 minutes — domain lists rarely change, and caching allows you to populate domain selector dropdowns without adding load to Mailgun's API on every dashboard refresh.

Alternatives

Frequently asked questions

Does Retool have a native Mailgun connector?

No, Retool does not have a dedicated native Mailgun connector. You connect via a REST API Resource using Mailgun's API key in Basic Auth with 'api' as the fixed username. The setup takes about 20 minutes and gives access to all Mailgun REST API endpoints for event tracking, suppression management, and delivery analytics.

Why does Mailgun Basic Auth require 'api' as the username?

Mailgun's API authentication was designed to use HTTP Basic Auth with a fixed username of 'api' and the actual API key as the password. This is a historical design choice — the 'api' username is a placeholder that Mailgun's authentication system expects as a constant, while the actual credential being validated is the API key in the password field. Unlike Mailchimp which accepts 'anystring', Mailgun specifically requires the literal string 'api'.

What is Mailgun's event retention period?

Mailgun retains events for different durations depending on your plan: 5 days on the free trial, 30 days on the Flex pay-as-you-go plan, and longer on Foundation and Scale plans (up to several months). For long-term audit trails, use a Retool Workflow to fetch events daily and persist them to a PostgreSQL database or another long-term store before they expire.

How do I check if a specific recipient email has ever bounced in Mailgun?

Query the bounces suppression list: GET /YOUR_DOMAIN/bounces/RECIPIENT_EMAIL in the Mailgun API. If the email address is in the bounce list, it returns a JSON object with the bounce code and error. If not found, it returns a 404. In Retool, create a query with this path bound to a text input for the email address, and display the result in a text component or alert the user if a bounce record exists.

Can I send emails through Mailgun from a Retool dashboard?

Yes, though it is less common. POST to /YOUR_DOMAIN/messages with form data including from, to, subject, and text or html fields. Set the Content-Type header to application/x-www-form-urlencoded for this endpoint. Most teams use Mailgun for monitoring in Retool rather than sending — Retool Workflows are better suited for automated email sending with error handling and retry logic.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Integrations are where projects stall

We wire Retool integrations like this one every week — auth, webhooks, edge cases included. Fixed-price builds from $13K, delivered in 6–10 weeks.

Talk to an integration engineer

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.