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?