Mailgun API returning 401

posted Originally published at dev.to 1 min read

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.

0 votes
0 votes

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

Building a Movie Recommendation API with Spring Boot

alejandrotg-codeverified - Apr 28

Create a simple email sender app

Sunny - Jul 12, 2025

I Wasted 10 Days on Backend Setup. Here’s What I’d Do in 2 Hours Now

buildbasekit - Apr 17
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!