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.

If you read this far, tweet to the author to show them you care. Tweet a Thanks

Thanks for sharing this clear and practical fix—sometimes it’s the small header details that trip us up the most! Have you found any other common pitfalls when working with Mailgun’s API, especially around regional differences or domain setup?

Hey James! Thank you for the question. Not really. Integrating with the Mailgun API is very straightforward. No other issues.

More Posts

Create a simple email sender app

Sunny - Jul 12

How Caffeine can boost your Spring caching capabilities

Ricardo Campos - Jul 9

Integrating Kafka Test Container for Local Development Environment

Amol Gote - Jun 8, 2024

DevLog 20250523: Firebase Auth

Methodox - May 23

A quick guide to adding wallets like Phantom and Solflare to your Solana DApp.

adewumi israel - Apr 12
chevron_left