fix(mail.service): use sendgrid api instead of nodemailer for better deliverability

This commit is contained in:
Amruth Pillai
2022-03-08 07:46:06 +01:00
parent e96b090904
commit 9df12194bf
11 changed files with 105 additions and 340 deletions

View File

@ -1,43 +1,36 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { readFileSync } from 'fs';
import { compile } from 'handlebars';
import { createTransport, Transporter } from 'nodemailer';
import { join } from 'path';
import SendGrid from '@sendgrid/mail';
import { User } from '@/users/entities/user.entity';
@Injectable()
export class MailService {
private readonly transporter: Transporter;
constructor(private configService: ConfigService) {
this.transporter = createTransport(
{
host: this.configService.get<string>('mail.host'),
port: this.configService.get<number>('mail.port'),
auth: {
user: this.configService.get<string>('mail.username'),
pass: this.configService.get<string>('mail.password'),
},
},
{
from: this.configService.get<string>('mail.from'),
}
);
SendGrid.setApiKey(this.configService.get<string>('sendgrid.apiKey'));
}
async sendForgotPasswordEmail(user: User, resetToken: string) {
async sendEmail(mail: SendGrid.MailDataRequired) {
return SendGrid.send(mail);
}
async sendForgotPasswordEmail(user: User, resetToken: string): Promise<void> {
const appUrl = this.configService.get<string>('app.url');
const url = `${appUrl}?modal=auth.reset&resetToken=${resetToken}`;
const templateSource = readFileSync(join(__dirname, 'assets/templates/forgot-password.hbs'), 'utf-8');
const template = compile(templateSource);
const html = template({ name: user.name, url });
await this.transporter.sendMail({
const mailData: SendGrid.MailDataRequired = {
from: {
name: this.configService.get<string>('sendgrid.fromName'),
email: this.configService.get<string>('sendgrid.fromEmail'),
},
to: user.email,
subject: 'Reset your Reactive Resume password',
html,
});
hideWarnings: true,
dynamicTemplateData: { url },
templateId: this.configService.get<string>('sendgrid.forgotPasswordTemplateId'),
};
await SendGrid.send(mailData);
return;
}
}