Coder
Coder

Reputation: 79

Why am I getting unauthorized error from Mailgun?

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));

Upvotes: 1

Views: 1350

Answers (2)

MichalRsa
MichalRsa

Reputation: 360

Well, while setting up the Mailgun I ran into two kinds of errors:

Unauthorized

https://documentation.mailgun.com/docs/mailgun/user-manual/get-started/#types-of-domains

I did not use the testing domain that Mailgun provides. This testing domain can be accessed under the left-side menu Send > Sending > Domains. YOUR_TESTING_DOMAIN has to be added in two different places.

const formData = require('form-data');
  const Mailgun = require('mailgun.js');
  const mailgun = new Mailgun(formData);
  const mg = mailgun.client({username: 'api', key: process.env.MAILGUN_API_KEY || 'key-yourkeyhere'});
  
  mg.messages.create('YOUR_TESTING_DOMAIN', {
    from: "Excited User <mailgun@YOUR_TESTING_DOMAIN>",
    to: ["VERIFIED_EMAIL"],
    subject: "Hello",
    text: "Testing some Mailgun awesomeness!",
    html: "<h1>Testing some Mailgun awesomeness!</h1>"
  })
  .then(msg => console.log(msg)) // logs response data
  .catch(err => console.log(err)); // logs any error

Forbidden

https://documentation.mailgun.com/docs/mailgun/user-manual/get-started/#sandbox-domain

I received this error because I did not authorize the recipient email in a testing environment

Sandbox domains can only be sent to authorized recipients.

Your Sandbox Domain allows:

Sending messages to lists with up to 5 authorized participants

To add the recipient email, in the left-hand menu navigate to Send > Sending > Overview

enter image description here

On the right side, you can see a place to provide email. Then confirm the action. Then put your VERIFIED_EMAIL as you can see on the code sample above.

Upvotes: 1

Manel
Manel

Reputation: 1654

Your credentials looks wrong.

Doc says :

  const mg = mailgun.client({username: 'api', key: process.env.MAILGUN_API_KEY || 'key-yourkeyhere'});

So in your case should be :

  const mg = mailgun.client({username: '5d....', key: '...'});

There is no public_key property. And if you use that key you must prefix it with "key-" not "pubkey-".

Upvotes: 0

Related Questions