node.jsmailgun

Unauthorized error by Mailgun using Node.js and mailgun.js package


I want to use Mailgun by Node.js and followed the exact code that mailgun site provided :

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('sandbox-123.mailgun.org', {
    from: "Excited User <mailgun@sandbox8dcd8ea3cce6409487a1093460a9d27a.mailgun.org>",
    to: ["test@example.com"],
    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

I am using mailgun.js@10.2.1 package.I have made a free account in Mailgun and created a key from API "Security-> Add new key" . I used that key instead of process.env.MAILGUN_API_KEY || 'key-yourkeyhere' and used a verified email instead of test@example.com. I also used public_key. I also used Sandbox Sending Key , but every time I get the error : [Error: Unauthorized] { status: 401, details: 'Forbidden', type: 'MailgunAPIError' } I would be very grateful if help me.


Solution

  • Try changing "sandbox-123.mailgun.org" to "sandbox8dcd8ea3cce6409487a1093460a9d27a.mailgun.org". That worked for me.

    See the example here:

    mg.messages.create('sandbox-123.mailgun.org', {
        from: "Excited User <mailgun@sandbox-123.mailgun.org>",
        to: ["test@example.com"],
        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 
    

    In the code example, "sandbox-123.mailgun.org" occurs twice, as the first argument and also the domain for the second argument