I’m trying to get start with Mailgun but i’m getting the error:
[Error: Unauthorized] {
status: 401,
details: 'Forbidden',
type: 'MailgunAPIError'
}
is this some user’s settings? I did copy both the private and public key, and the domain, from dashboard. I don’t know what’s wrong.
from code:
const formData = require('form-data');
const Mailgun = require('mailgun.js');
const mailgun = new Mailgun(formData);
const mg = mailgun.client({
username: 'api',
key: '5d....',
public_key: 'pubkey-....'
});
mg.messages.create('sandboxyyyyyyyy.mailgun.org', {
from: "Excited User [email protected]",
to: ["[email protected]"],
subject: "Hello",
text: "Testing some Mailgun awesomness!",
html: "<h1>Testing some Mailgun awesomness!</h1>"
})
.then(msg => console.log(msg))
.catch(err => console.log(err));
2
Answers
Your credentials looks wrong.
Doc says :
So in your case should be :
There is no
public_key
property. And if you use that key you must prefix it with "key-" not "pubkey-".When dealing with unauthorized errors from Mailgun, there are several common issues to consider:
Incorrect API Key: Ensure that the API key you are using is correct. It’s easy to make a mistake while copying the API key. Double-check the API key in your Mailgun dashboard and ensure it matches the one in your code.
Wrong Domain: Make sure the domain you’re using in your mg.messages.create call matches the domain configured in your Mailgun account. The error might occur if there’s a mismatch.
Incorrect Endpoint: Mailgun provides different API endpoints for EU and US servers. Ensure you’re using the correct endpoint for your account’s region.
Key Permissions: Verify that the API key you are using has the correct permissions for the action you’re trying to perform. Some keys might have limited permissions.
Key Activation: If you have recently created the API key, ensure that it has been activated. Sometimes there might be a delay in activation.
Code Syntax: Check for any syntax errors in your code. Ensure that the API key and other parameters are being passed correctly.
Dependency Issues: Ensure that the dependencies (form-data, mailgun.js) are correctly installed and compatible with your environment.
IP Address Restrictions: If your Mailgun account has IP address restrictions, make sure the requests are coming from an allowed IP address.
Account Status: Check if your Mailgun account is in good standing and not suspended or restricted for some reason.
In your specific case, the key seems to be correctly configured, but ensure that the domain sandboxyyyyyyyy.mailgun.org is exactly the same as the one listed in your Mailgun dashboard. If all these factors are correctly configured and the issue persists, contacting Mailgun support for a more detailed investigation would be advisable.