Mailgun API returning 401

1 9 16
calendar_todayschedule1 min read
— Originally published at dev.to

How to solve 401 error on Mailgun API request

Disclaimer: This solution is for a Spring Boot API, but might help you on different languages.

I've been fighting this error for over one hour, and the solution is quite simple.

When authenticating your API request programmatically, make sure you add a simple Authorization header instead of a BasicAuth header directly.

In Java, usually you have a couple of options to add Headers to a request. Where you could call a method that defined the header's name or a generic one where you define both the header name and value.

Do this:

headers.set(HttpHeaders.AUTHORIZATION, basicAuth("api", appConfig.getMailgunApiKey()));

And don't do this:

headers.setBasicAuth(basicAuth("api", appConfig.getMailgunApiKey()));

For reference, in case you're wondering:

private String basicAuth(String username, String password) {
  String auth = username + ":" + password;
  return "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
}

Now if you're still getting 401, here are some possible generic solutions for you:

  • API Key: double check the API key, if it's being applied and used correctly;
  • Domain Verification: Although I'm not 100% sure this is a blocker, make sure your domain is verified and all check are green;
  • Region Mismatch: If you're working within the EU region, you might have to se the EU in the URL directly: https://api.eu.mailgun.net/v3/... instead of the api.mailgun.net directly.

That's it. Thank you.

2 Comments

0 votes
0 votes
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Merancang Backend Bisnis ISP: API Pelanggan, Paket Internet, Invoice, dan Tiket Support

Masbadar - Mar 13

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Spring Boot File Upload Performance: Why Your API Gets Slow Under Load (And How to Fix It)

buildbasekit - May 20

Building a Movie Recommendation API with Spring Boot

alejandrotg-code - Apr 28

Create a simple email sender app

Sunny - Jul 12, 2025
chevron_left
2.4k Points26 Badges
Joinville, Brazillinktr.ee/ricardo.rmcampos
4Posts
18Comments
I'm a professional software developer with many years of experience. My stronger skills are in the b... Show more

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!