|
| 1 | +import { green } from 'colorette' |
| 2 | +import fs from 'fs' |
| 3 | +import Handlebars from 'handlebars' |
| 4 | +import path from 'path' |
| 5 | +import { env } from '~/config/env' |
| 6 | +import { logger } from '~/config/logger' |
| 7 | +import { smtp } from '~/config/smtp' |
| 8 | +import { readHTMLFile } from '~/lib/fs/read-file' |
| 9 | +import ErrorResponse from '~/lib/http/errors' |
| 10 | +import { currentDir } from '~/lib/string' |
| 11 | + |
| 12 | +/** |
| 13 | + * Returns the path to the email template |
| 14 | + * @param htmlPath - the path to the email template |
| 15 | + * @returns the path to the email template |
| 16 | + */ |
| 17 | +function _emailTemplatePath(htmlPath: string) { |
| 18 | + const _path = path.resolve(`${currentDir}/public/email-template/${htmlPath}`) |
| 19 | + |
| 20 | + const msgType = green('email template') |
| 21 | + logger.info(`${msgType} - ${_path} exists`) |
| 22 | + |
| 23 | + return _path |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Sends an email |
| 28 | + * @param _path - the path to the email template |
| 29 | + * @param data - the data to be sent |
| 30 | + * @returns the email template |
| 31 | + */ |
| 32 | +async function _sendMail(_path: string, data: any) { |
| 33 | + if (!fs.existsSync(_path)) { |
| 34 | + throw new ErrorResponse.BadRequest('invalid template path ') |
| 35 | + } |
| 36 | + |
| 37 | + const html = await readHTMLFile(_path) |
| 38 | + const template = Handlebars.compile(html) |
| 39 | + const htmlToSend = template(data) |
| 40 | + |
| 41 | + await smtp.send({ |
| 42 | + to: data.email, |
| 43 | + subject: data.subject, |
| 44 | + text: data.text, |
| 45 | + html: htmlToSend, |
| 46 | + }) |
| 47 | +} |
| 48 | + |
| 49 | +type SendEmailRegistrationParams = { |
| 50 | + fullname: string |
| 51 | + email: string |
| 52 | + url_token: string |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Sends an email to the user |
| 57 | + * @param values - the data to be sent |
| 58 | + */ |
| 59 | +export async function SendEmailRegistration(values: SendEmailRegistrationParams) { |
| 60 | + const _path = _emailTemplatePath('register.html') |
| 61 | + |
| 62 | + const { fullname, url_token } = values |
| 63 | + const subject = `${fullname}, Thank you for registering on the ${env.APP_NAME} App` |
| 64 | + const text = `Please click the link below to verify your email: ${env.APP_URL}/verify/${url_token}` |
| 65 | + |
| 66 | + const data = { ...values, subject, text, APP_NAME: env.APP_NAME } |
| 67 | + await _sendMail(_path, data) |
| 68 | +} |
0 commit comments