First install the package.
yarn add mailgun.js
yarn add form-data
Mailgun code is separated into service.
Create a new service and create a method to send mail.
The part to get the secret key using ConfigService is also created.
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Mailgun from 'mailgun.js';
import FormData from 'form-data';@Injectable()
export class MailgunService {
constructor(private readonly config: ConfigService) {} // mailgun secret key
private MAILGUN_KEY = this.config.get<string>('MAILGUN_KEY');
private MAILGUN_DOMAIN = this.config.get<string>('MAILGUN_DOMAIN'); private client = new Mailgun(FormData).client({
username: 'api',
key: this.MAILGUN_KEY,
}); /**
* Send via API
*
* @param data
*/
async sendMail(data) {
this.client.messages
.create(this.MAILGUN_DOMAIN, data)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.error(err);
});
}
}
The API to send mail is implemented in the app controller.
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { MailgunService } from './providers/mailgun/mailgun.service';@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly mailgunService: MailgunService,
) {} @Get()
getHello(): string {
return this.appService.getHello();
} @Get('mail')
getMail() {
const messageData = {
from: 'Excited User <me@samples.mailgun.org>',
to: 'foo@example.com, bar@example.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomeness!',
}; this.mailgunService.sendMail(messageData);
}
}
If the module is even coded and executed, an error may occur.
A TypeError is raised with the message this.FormDataConstructor is not a constructor.
To prevent this, add esModuleInterop to true in tsconfig.json.
I share the full code here.