Search code examples
node.jsexpressmailgunmailgun-api

Mailgun EU domain throws 401 in Node.js


I am integrating mailgun eu domain but I don't know why the eu domain is not working in my node.js application. My mailgun domain is also verified.

When I try to create a message using the mailgun api it always throws a 401 Forbidden error.

I also checked my MAILGUN_SECRET_KEY and it is also correct.

Here my code

import 'dotenv/config'
import formData from 'form-data';
import Mailgun from 'mailgun.js';

class MailgunService {    

    constructor() {
        this.apiKey = process.env.MAILGUN_SECRET_KEY;
        this.domain = process.env.MAILGUN_DOMAIN;
        this.mailgunClient = this.setupClient();
    }

    setupClient() {
        const mailgun = new Mailgun(formData);
        return mailgun.client({
            url: 'https://api.eu.mailgun.net', // default
            username: 'api',
            key: this.apiKey,
        });
    }

    sendMail() {
        const messageData = {
            from: "replace_with_your_email",
            to: "replace_with_your_email",
            subject: "Hello",
            text: "Testing some Mailgun awesomeness!"
        };

        this.mailgunClient.messages.create(this.domain, messageData)
            .then(msg => console.log(msg)) // logs response data
            .catch(err => console.log(err)); // logs any error
    }
}

export default MailgunService;

Error:

enter image description here

I expect I can send emails using an EU domain.


Solution

  • It is likely because you need to explicitly whitelist your server's IP address with Mailgun via the IP Allowlist.