How-To

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 HussainSohail Hussain9 min read

Short 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.

CauseTypical symptomFix
Wrong region endpointKey is valid, domain exists, still 401Set the client URL to https://api.eu.mailgun.net for EU domains
Wrong key type or roleSending works but domain calls fail, or the reverseUse an account API key for account calls; a sending key only for that domain's sending
Key empty, quoted or paddedWorks locally, fails on the serverCheck the env variable at runtime; strip quotes and newlines
Deleted, rotated or other-account keyWorked before, now 401Create a new key and update every service
Domain not on this accountKey fine, domain name wrongPass the domain exactly as shown in the dashboard
Old library syntaxCopied code from an older tutorialUse username: "api" and key with mailgun.js
IP allowlist or proxyFails only from certain hostsCheck 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.

  1. Open your Mailgun dashboard and note whether the address is app.mailgun.com or app.eu.mailgun.com.
  2. If it's the EU dashboard, set the client's url to https://api.eu.mailgun.net.
  3. 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.

  1. 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.
  2. 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.
  3. Don't use the Verifications Public Key. It sits on the same API Security page but is for address validation, not sending.
  4. Check the value your app actually sees. Log whether process.env.MAILGUN_API_KEY is set and its length, never the key itself. A trailing newline in a .env file or quotes copied into the value both break authentication.
  5. 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 pass example.com.
  • Leave out https:// and any path.
  • Don't use localhost or 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-js package use apiKey and domain. With mailgun.js, the username must be "api" and the option is key.
  • 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 Authorization header 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 api and the option is key
  • 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.

strategymailgunerror-codes
Share this article
Sohail Hussain

Sohail Hussain

Founder & CEO at Mailneo

Building Mailneo — AI-powered email marketing for growing businesses.

Ready to supercharge your email marketing?

Start sending smarter emails with AI-powered campaigns. No credit card required.

Get Started Free