Reputation: 835
I tried running this code from their npmjs documentation.
const mailgun = new Mailgun(FormData);
const mg = mailgun.client({ username: 'api', key: MY_MAILGUN_API, url: 'https://api.eu.mailgun.net'})
mg.messages.create('sandbox-123.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)) // logs response data
.catch(err => console.error(err)); // logs any error
and it throws error
[Error: Unauthorized] {
status: 401,
details: 'Forbidden',
type: 'MailgunAPIError'
}
and i have no idea where the problem is. googled and nothing relevant comes up for me.
MY_MAILGUN_API - copied from my account
[email protected] - in code i have email that i can access
Upvotes: 1
Views: 369
Reputation: 11
The 401 error indicates that the sending API key is invalid.
In Mailgun home, you have to go to the "Sending section" and select the domain from which you want to send emails. Then click on "Domain settings" and click on "Sending API keys". You have to create a new sending key. And you should have no problems.
Simple steps for create a new sending api key
Example Code:
const SENDING_KEY = 'YOUR_SENDING_KEY';
const DOMAIN = 'YOUR_DOMAIN_NAME';
const mailgun = new Mailgun(formData);
const client = mailgun.client({
username: 'api',
key: SENDING_KEY,
url: 'https://api.eu.mailgun.net'
});
const messageData = {
from: 'Excited User <[email protected]>',
to: '[email protected], [email protected]',
subject: 'Hello',
text: 'Testing some Mailgun awesomeness!'
};
client.messages.create(DOMAIN, messageData)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.error(err);
});
Upvotes: 1