Mailgun 401 Unauthorized (MailgunAPIError): Cause and Fix
Mailgun returns a 401 when the API key, the domain or the region in your request doesn't match your account. Use a key from the same account, send through a domain that key can access, and point the client at api.eu.mailgun.net if the domain was created in the EU region.
Sohail Hussain9 min readShort answer
- A 401 from Mailgun means the credentials were rejected: the API key, the domain and the API region (US or EU) don't belong together.
- Check the region first: EU domains must call api.eu.mailgun.net, not the default api.mailgun.net. Then confirm you're using a current key of the right type, and pass the domain exactly as Mailgun lists it.
- Test with a plain curl request to take your code out of the picture.
You ran a send from Node and got this:
[Error: Unauthorized] { status: 401, details: 'Forbidden', type: 'MailgunAPIError' }
status: 401 is the HTTP status. type: 'MailgunAPIError' is the label the mailgun.js client puts on any failed API response. The details: 'Forbidden' text is simply the message that came back with it; the mismatch with "Unauthorized" doesn't tell you anything extra. Nothing was queued or sent, and no SMTP code is involved because the request failed at the HTTP API.
Why it happens
Mailgun authenticates API calls with HTTP Basic auth. The username is api and the password is your Mailgun API key. A 401 means that pair didn't check out against the endpoint you called. The causes below are ordered by how often I'd expect them.
| Cause | Typical symptom | Fix |
|---|---|---|
| Wrong region endpoint | Key is valid, domain exists, still 401 | Set the client URL to https://api.eu.mailgun.net for EU domains |
| Wrong key type or role | Sending works but domain calls fail, or the reverse | Use an account API key for account calls; a sending key only for that domain's sending |
| Key empty, quoted or padded | Works locally, fails on the server | Check the env variable at runtime; strip quotes and newlines |
| Deleted, rotated or other-account key | Worked before, now 401 | Create a new key and update every service |
| Domain not on this account | Key fine, domain name wrong | Pass the domain exactly as shown in the dashboard |
| Old library syntax | Copied code from an older tutorial | Use username: "api" and key with mailgun.js |
| IP allowlist or proxy | Fails only from certain hosts | Check the allowlist; run curl from the same machine |
Fix 1: match the region
Mailgun runs separate regions with separate endpoints. The API base URL is https://api.mailgun.net/ for the US region and https://api.eu.mailgun.net/ for the EU region. A key and domain created in one region aren't recognized by the other region's API host.
To confirm your region, look at the dashboard address. US accounts use app.mailgun.com and EU accounts use app.eu.mailgun.com.
- Open your Mailgun dashboard and note whether the address is
app.mailgun.comorapp.eu.mailgun.com. - If it's the EU dashboard, set the client's
urltohttps://api.eu.mailgun.net. - Redeploy and retry.
import formData from "form-data";
import Mailgun from "mailgun.js";
const mailgun = new Mailgun(formData);
const mg = mailgun.client({
username: "api",
key: process.env.MAILGUN_API_KEY,
url: "https://api.eu.mailgun.net", // leave out for US domains
});
Other EU endpoints differ too. Outgoing SMTP uses smtp.eu.mailgun.org, and click and open tracking uses eu.mailgun.org. If you also send by SMTP, check those hosts as well, see Mailgun's help article on moving a domain between regions.
Fix 2: check the key type and value
For the API you need an Account API Key or a Domain Sending Key. They aren't interchangeable.
- Decide which you have. A Domain Sending Key can send messages only through the domain it was created on. Used for domain management or another domain, it will be refused.
- Check the key's role if it's an account key. Mailgun assigns every API key a role (Admin, Developer, Support or Analyst), and the Domains permission is read-only for Analyst and Support (Mailgun's table lists Analyst and Support as Read, Admin and Developer as Read/Write). A read-only role can't perform write actions.
- Don't use the Verifications Public Key. It sits on the same API Security page but is for address validation, not sending.
- Check the value your app actually sees. Log whether
process.env.MAILGUN_API_KEYis set and its length, never the key itself. A trailing newline in a.envfile or quotes copied into the value both break authentication. - Create a fresh key if in doubt. Open your Profile Menu, choose API Security, then click Add new key. The key is shown only once, in a pop-up after creation, so copy it straight into your secrets store.
Rotate leaked keys
If you pasted a key into a forum post, a chat or a public repo while debugging, treat it as leaked. Delete it in API Security and create a new one.
Fix 3: check the domain
The domain in your call must exist on the same Mailgun account and region as the key.
await mg.messages.create("mg.example.com", {
from: "Sender <postmaster@mg.example.com>",
to: ["person@example.org"],
subject: "Test",
text: "Hello",
});
- Use the domain exactly as Mailgun lists it. If you added
mg.example.com, don't passexample.com. - Leave out
https://and any path. - Don't use
localhostor an IP address. Mailgun requires a valid domain that can be verified through DNS. - If you moved the domain to another Mailgun account, old keys stop working. The API key and Domain Sending Keys have different values once the domain is added to the new account.
- Sandbox domains work only for testing. They are limited to authorized recipients. That limit causes a different error than a 401, but people often swap in a sandbox domain and the wrong key at the same time.
Fix 4: test with curl
Run this outside your app, on the same machine or container where the error occurs. Use the EU host if your domain is EU.
curl -s --user "api:YOUR_API_KEY" \
https://api.mailgun.net/v3/domains
A 401 here means the key or region is wrong, not your code. A JSON list of domains means the key works for that region, so look at the domain name or at how your app loads the key.
An account key is the right tool for that call. A domain sending key may be refused on /v3/domains even though it's valid for sending, so test it with a send:
curl -s --user "api:YOUR_API_KEY" \
https://api.mailgun.net/v3/mg.example.com/messages \
-F from="Test <postmaster@mg.example.com>" \
-F to="you@example.org" \
-F subject="Test" \
-F text="Hello"
Swap the host, not just the key
If curl returns 401 on the US host with a key you trust, repeat it against the EU host before creating new keys. A region mismatch is the cheapest thing to rule out.
Fix 5: rule out the less common causes
- Old library syntax. Examples written for the older
mailgun-jspackage useapiKeyanddomain. Withmailgun.js, the username must be"api"and the option iskey. - IP allowlist. If you enabled one on the account, requests from a new server or a serverless platform with changing IPs can be refused. Mailgun's partners mention relaxing the allowlist temporarily when syncing domains, which suggests it's a known source of failures.
- Header rewriting. A proxy or gateway that strips or replaces the
Authorizationheader produces a 401. The curl test from the same host catches this. - Account state. If every check passes, look for notices in the dashboard about the account or domain.
- Deleted or disabled key. Mailgun's own troubleshooting for another tool says to confirm the key hasn't been disabled or deleted in API Security.
Checklist before you try again
- Dashboard region matches the API URL in your client
- Key is current, copied cleanly and exists in API Security
- Key type fits the call (account key for account calls, sending key for its own domain)
- Domain is spelled exactly as in Mailgun, with no protocol
- Username is
apiand the option iskey - Curl from the same host returns a domain list or accepts a message
How to prevent it
Keep the region in config next to the key rather than hard-coding it, so staging and production can differ. Fail at startup if the key variable is empty. Use a domain sending key for production sending, so a leak exposes less. After rotating a key, restart every service that loaded the old one.
If nothing works
Contact Mailgun support through your account's help center. Include the domain, the region, the last four characters of the key (never the whole key), the UTC timestamp of a failing request, the endpoint called, the full response body and the curl command you tried.
Subject: 401 Unauthorized on API requests for {your-domain}
Hello,
Requests to the Mailgun API return 401 Unauthorized.
Domain: {your-domain}
Region: {US or EU}
Endpoint: {full URL}
Key: ends in {last 4 characters}, type {account or sending}
Time (UTC): {timestamp}
Response: [Error: Unauthorized] { status: 401, details: 'Forbidden', type: 'MailgunAPIError' }
I confirmed the region and domain, and a curl request from the same host
gives the same result. Can you check whether the key is active and allowed
to access this domain?
Thanks
Common questions
Why does the error say both "Unauthorized" and "Forbidden"?
The client combines the HTTP 401 status with the message text from the response. Treat it as one authentication failure and work through region, key and domain.
Can I use the same key for US and EU domains?
Don't assume so. Mailgun's regions are separate, with their own endpoints, so a domain created in one region is served by that region's API host. If you have domains in both, store a region setting alongside each key.
My key worked yesterday. What changed?
Usually the key was rotated or deleted, the domain moved to another account, or an environment variable didn't load in a new deployment. Check API Security first.
Does a 401 mean my domain's DNS is broken?
No. DNS problems show up later, as failed domain verification or delivery issues. Once the API accepts your calls, how to set up SPF, DKIM and DMARC and our SPF generator cover the records.
Explore: Email Marketing Strategy
Related Articles
Mailgun: "The 'address' parameter should be a valid email address"
Mailgun returns this error when the address sent to its mailing list API is empty or malformed. The usual causes are a blank field in your export, stray whitespace, a display name mixed into the address, or an unencoded plus sign. Find the bad value, clean it, and resend.
414 Request-URI Too Large in n8n's Amazon SES node: fix
The error 414 Request-URI Too Large in n8n's AWS SES node means a server in the path refused a request whose URL was too long, which a long HTML body can cause when it travels in the URL. Send through the SES v2 API with an HTTP Request node, or use SES SMTP.
Access denied, bad outbound sender: Outlook cold email fix
"Access denied, bad outbound sender" (550 5.1.8) means Microsoft 365 has put your mailbox on its restricted users list for spam-like sending. An admin must unblock it under Restricted entities in the Microsoft Defender portal. Then clean your list, lower your volume and resume gradually.
Acoustic Campaign "Application error" on login: bookmark fix
Acoustic Campaign shows "application error" at login when you open it from a bookmark saved while you were logged in, because the bookmark carries the old session. Log out, type your pod URL (campaign-us-[X].goacoustic.com) into the address bar, log in, then save a fresh bookmark.
Ready to supercharge your email marketing?
Start sending smarter emails with AI-powered campaigns. No credit card required.
Get Started Free