I keep receiving a 401 unauthorized error while attempting to send emails using Mailgun API in my NestJS app. I’ve verified my API keys and domain configurations, yet the issue continues. Below is my email service code implementation:
import { Injectable } from '@nestjs/common';
import * as MailgunJS from 'mailgun-js';
import { IEmailData } from './interfaces/email.interface';
import { ConfigService } from '../config/config.service';
@Injectable()
export class EmailService {
private mailgunClient: MailgunJS.Mailgun;
constructor(private readonly config: ConfigService) {
this.mailgunClient = MailgunJS({
apiKey: this.config.get('MAILGUN_KEY'),
domain: this.config.get('MAILGUN_DOMAIN'),
});
}
sendEmail(emailData: IEmailData): Promise<MailgunJS.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 configuration for my client shows:
Mailgun {
username: 'api',
apiKey: '3a5f7829db970c6e92f8bc63e27xxx-xxx-xxx',
domain: 'my-domain.com',
auth: 'api:3a5f7829db970c6e92f8bc63e27xxx-xxx-xxx',
host: 'api.mailgun.net',
endpoint: '/v3',
protocol: 'https:',
port: 443
}
Here is the email data that I am attempting 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 the cause of this authorization error?