Getting 401 unauthorized error when using Mailgun API

I’m having trouble with my email service implementation using Mailgun API in my Node.js application. Every time I attempt to send an email, I receive a 401 unauthorized error. I’ve double-checked my API credentials and domain settings, but the issue persists. Here’s my email service implementation:

import { Injectable } from '@nestjs/common};
import * as MailgunAPI from 'mailgun-js';
import { IEmailData } from './interfaces/email.interface';
import { AppConfigService } from '../config/app-config.service';

@Injectable()
export class EmailService {
  private mailgunClient: MailgunAPI.Mailgun;

  constructor(private readonly appConfig: AppConfigService) {
    this.mailgunClient = MailgunAPI({
      apiKey: this.appConfig.getValue('MAILGUN_KEY'),
      domain: this.appConfig.getValue('MAILGUN_DOMAIN'),
    });
  }

  sendEmail(emailData: IEmailData): Promise<MailgunAPI.messages.SendResponse> {
    console.log(emailData);
    console.log(this.mailgunClient);
    return new Promise((resolve, reject) => {
      this.mailgunClient.messages().send(emailData, function (err, response) {
        if (err) {
          console.log(err);
          reject(err);
        }
        resolve(response);
      });
    });
  }
}

The client configuration shows:

Mailgun {
  username: 'api',
  apiKey: '8f5a2c9e3b7d4e1a92f6b8c5d3e7xxx-xxx-xxx',
  domain: 'my-app-domain.com',
  auth: 'api:8f5a2c9e3b7d4e1a92f6b8c5d3e7xxx-xxx-xxx',
  host: 'api.mailgun.net',
  endpoint: '/v3',
  protocol: 'https:'
}

My email payload:

{
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Account Verification',
  html: '<h3>Welcome [email protected]!</h3><p>Please verify your account.</p>'
}

What could be causing this authentication issue?

make sure your mailgun settings match with your region. if you’re on EU, use the right endpoint! and double-check that your API key has the ‘key-’ prefix. it’s easy to mix it up.

Had this exact problem last month - turned out to be domain verification. Your domain might show up in the client config, but check your Mailgun dashboard to make sure it actually says “verified,” not “pending” or “unverified.” I see you’re using ‘my-app-domain.com’ as the domain but your from address is ‘[email protected]’. These need to match exactly with what’s in Mailgun. One more thing - if you’re using a sandbox domain for production, that’ll cause auth errors. Sandbox domains can only send to verified recipients.

You might be using the wrong API key. I made this mistake when copying from the dashboard - there’s multiple keys there and it’s easy to grab the wrong one. Double-check your environment variables are loading right by logging the first few characters. Config services don’t always pull values like you’d expect. Also watch for whitespace in your API key - trailing spaces will break things if you’re copying from a file. The mailgun-js library is pretty outdated too. Try switching to the official mailgun.js SDK since it handles auth differently and might fix your problem.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.