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.