import { Injectable } from '@nestjs/common'; import { User } from '../entities/user.entity'; import { PasswordResetToken } from '../entities/password-reset-token.entity'; import * as nodemailer from 'nodemailer'; import * as handlebars from 'handlebars'; export class Email { from: string; to: string[]; subject: string; text: string; html?: string; } const WELCOME_MAIL_TEMPLATE: HandlebarsTemplateDelegate<{ username: string; link: string; }> = handlebars.compile( ` Hello {{username}}, You've been added to QiVisor. To complete your registration click the link below: {{link}} Best, QiVisor `.trim(), ); const PASSWORD_RESET_MAIL_TEMPLATE: HandlebarsTemplateDelegate<{ username: string; link: string; }> = handlebars.compile( ` Hello {{username}}, To reset your password click the link below: {{link}} Best, QiVisor `.trim(), ); @Injectable() export class MailerService { async sendWelcomeEmail(user: User, token: PasswordResetToken) { const fromEmail = process.env.SMTP_FROM_EMAIL || 'registrationdev - qivisor@viravix.com'; const email: Email = { from: `"QiVisor Dev version" <${fromEmail}>`, to: [`"${user.username}" <${user.email}>`], subject: 'Welcome to QiVisor', text: WELCOME_MAIL_TEMPLATE({ username: user.username, link: token.token, }), }; await this.sendEmail(email); } async sendResetPasswordEmail(user: User, token: PasswordResetToken) { const fromEmail = process.env.SMTP_FROM_EMAIL || 'password-reset-dev-qivisor@viravix.com'; const email: Email = { from: `"QiVisor Dev version Password Reset" <${fromEmail}>`, to: [`"${user.username}" <${user.email}>`], subject: 'Password Reset', text: PASSWORD_RESET_MAIL_TEMPLATE({ username: user.username, link: token.token, }), }; await this.sendEmail(email); } async sendEmail(email: Email) { const testAccount = process.env.SMTP_HOST ? {} : await nodemailer.createTestAccount(); const transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST || 'smtp.ethereal.email', port: process.env.SMTP_PORT || 587, secure: false, auth: { user: process.env.SMTP_USER || testAccount.user, pass: process.env.SMTP_PASSWORD || testAccount.pass, }, }); const info = await transporter.sendMail(email); console.log('Message sent: ', info); if (!process.env.SMTP_HOST) { console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info)); } } }