DEV Community

Ricardo Campos
Ricardo Campos

Posted on

Mailgun API returning 401

How to solve 401 error on Mailgun API request

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

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

The reason I'm creating this post, even in AI times, is that Claude wasn't able to point me clearly the issue, so, here it goes:

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

Do this:

headers.set(HttpHeaders.AUTHORIZATION, basicAuth("api", appConfig.getMailgunApiKey()));
Enter fullscreen mode Exit fullscreen mode

And don't do this:

headers.setBasicAuth(basicAuth("api", appConfig.getMailgunApiKey()));
Enter fullscreen mode Exit fullscreen mode

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));
}
Enter fullscreen mode Exit fullscreen mode

Now if you're still getting 401, I'll leave some items for you to double check:

  • 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 EU region, you might have to se the EU URL: https://api.eu.mailgun.net/v3/... instead of the api.mailgun.net directly.

That's it. Thank you. Follow me for more. I'll be posting small fixes like this more often.

Top comments (0)