I’m having trouble sending emails through Mailgun in my Node.js application. Every time I try to send an email, I get a 401 unauthorized error. I’m using NestJS framework and here’s my email service implementation:
import { Injectable } from '@nestjs/common';
import * as MailgunSDK from 'mailgun-js';
import { IEmailData } from './interfaces/email.interface';
import { ConfigService } from '../config/config.service';
@Injectable()
export class EmailService {
private mailgunClient: MailgunSDK.Mailgun;
constructor(private readonly configService: ConfigService) {
this.mailgunClient = MailgunSDK({
apiKey: this.configService.get('MAILGUN_KEY'),
domain: this.configService.get('MAILGUN_DOMAIN'),
});
}
sendEmail(emailData: IEmailData): Promise<MailgunSDK.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 looks correct when I log it:
Mailgun {
username: 'api',
apiKey: 'key-abc123def456ghi789jkl012mnp345-qrs-tuv',
domain: 'my-website.com',
auth: 'api:key-abc123def456ghi789jkl012mnp345-qrs-tuv',
host: 'api.mailgun.net',
endpoint: '/v3',
protocol: 'https:',
port: 443
}
And here’s the email data I’m trying to send:
{
from: '[email protected]',
to: '[email protected]',
subject: 'Account Verification',
html: '<h3>Hello [email protected]!</h3><p>Please verify your account.</p>'
}
What could be causing this 401 error? I’ve double checked my API key and domain settings but still getting the same forbidden message.