Home > Back-end >  Sending an email template on request?
Sending an email template on request?

Time:08-29

how to choose a template for sending an email?
I get a request for example: reset_password. But I also have registrations (signup).
How do I send the letter that I need on request?
I want to http://localhost:3000/sendmail?apiKey=test&type=reset_password

reset_password: http://localhost:3000/sendmail?apiKey=test&type=reset_password
signup: http://localhost:3000/sendmail?apiKey=test&type=signup
if it is a registration, a registration or password reset letter
How do I process this? The request sends the template that you need

const transporter = require("./transporter");
const ejs = require('ejs')
const path = require('path')


const mailer = async (type, to) => {
      what handler?
     const reset_password = path.join(__dirname, "../reset_password.ejs"),
     const signup = path.join(__dirname, "../signup.ejs")

    const data = await ejs.renderFile(reset_password,signup { to });


    const mainOptions = {
      from: 'test', 
      to: to,
      text: "Hello world?",
      subject: 'dw', 
      html: data
    };

    return transporter.sendMail(mainOptions) 
  };


module.exports = mailer;  

How do I make it so: If a "reset_password" request comes, an email with a different email template is sent, if it is "signup" an email with a different template is sent. in the type request comes reset_password or signup I don't understand how to make it so that each request would have different email templates ps: different type. and different letter templates

CodePudding user response:

First - fix your mailer code

const mailer = async (type, to) => {
     const template = path.join(__dirname, `../${type}.ejs`)

    const data = await ejs.renderFile(template, { to });


    const mainOptions = {
      from: 'test', 
      to: to,
      text: "Hello world?",
      subject: 'dw', 
      html: data
    };

    return transporter.sendMail(mainOptions) 
  };

Then , ensure to send to the mailer function the type parameter (first one) using

const { apiKey, type } = req.query
const email = '...' // todo: grab user email
mailer(type, email)
  • Related