mail.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import nodemailer from "nodemailer";
  2. import path from "path";
  3. import fs from "fs";
  4. import { resetMailText, verifyMailText } from "./text";
  5. import { CustomError } from "../utils";
  6. import env from "../env";
  7. const mailConfig = {
  8. host: env.MAIL_HOST,
  9. port: env.MAIL_PORT,
  10. secure: env.MAIL_SECURE,
  11. auth: {
  12. user: env.MAIL_USER,
  13. pass: env.MAIL_PASSWORD
  14. }
  15. };
  16. const transporter = nodemailer.createTransport(mailConfig);
  17. export default transporter;
  18. // Read email templates
  19. const resetEmailTemplatePath = path.join(__dirname, "template-reset.html");
  20. const verifyEmailTemplatePath = path.join(__dirname, "template-verify.html");
  21. const resetEmailTemplate = fs
  22. .readFileSync(resetEmailTemplatePath, { encoding: "utf-8" })
  23. .replace(/{{domain}}/gm, env.DEFAULT_DOMAIN);
  24. const verifyEmailTemplate = fs
  25. .readFileSync(verifyEmailTemplatePath, { encoding: "utf-8" })
  26. .replace(/{{domain}}/gm, env.DEFAULT_DOMAIN);
  27. export const verification = async (user: User) => {
  28. const mail = await transporter.sendMail({
  29. from: env.MAIL_FROM || env.MAIL_USER,
  30. to: user.email,
  31. subject: "Verify your account",
  32. text: verifyMailText.replace(
  33. /{{verification}}/gim,
  34. user.verification_token
  35. ),
  36. html: verifyEmailTemplate.replace(
  37. /{{verification}}/gim,
  38. user.verification_token
  39. )
  40. });
  41. if (!mail.accepted.length) {
  42. throw new CustomError("Couldn't send verification email. Try again later.");
  43. }
  44. };
  45. export const resetPasswordToken = async (user: User) => {
  46. const mail = await transporter.sendMail({
  47. from: env.MAIL_USER,
  48. to: user.email,
  49. subject: "Reset your password",
  50. text: resetMailText
  51. .replace(/{{resetpassword}}/gm, user.reset_password_token)
  52. .replace(/{{domain}}/gm, env.DEFAULT_DOMAIN),
  53. html: resetEmailTemplate
  54. .replace(/{{resetpassword}}/gm, user.reset_password_token)
  55. .replace(/{{domain}}/gm, env.DEFAULT_DOMAIN)
  56. });
  57. if (!mail.accepted.length) {
  58. throw new CustomError(
  59. "Couldn't send reset password email. Try again later."
  60. );
  61. }
  62. };