Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
Creating an express middleware to send emails

I've been trying to make an express middleware that sends an email using Nodemailer after the previous middleware finishes. I've come up with a few different designs, but ultimately each different version has it's drawback.

Ultimately, I would like the middleware to have a response from the previous middleware. If it is a success, then send a success email, otherwise, send an error email.

I came up with a dual design where one variation pushes to an error middleware, and a success leads to the next middleware. This contains some slight issues of sending multiple headers, specifically on an the second middleware erroring. I could say, if the mail errors out, do nothing. But that doesn't seem right. If anyone has any suggestions on a good design, that would be great.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

From what you described, I would suggest not to create different middleware for that, but to just create one generic email function that would handle different type of messages. Then, just use that function in the first middleware and pass different parameters based on use case (success/error).

email-controller.js

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  host: process.env.EMAIL_HOST,
  port: process.env.EMAIL_PORT,
  secure: true,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASSWORD,
  },
});

exports.send_email_message = (send_to, subject, message) => {

  return new Promise((resolve, reject) => {

    const email_message = {
      from: { name: process.env.EMAIL_FRIENDLY_NAME },
      to: send_to,
      subject: subject,
      text: message
    };

    transporter.sendMail(email_message).then(() => {
      resolve(true);
    }).catch((error) => {
      reject(false);
    });

  })

}

custom-router.js

const { send_email_message } = require('./email-controller');
const express = require('express');
const router = express.Router();

router.get('/custom-middleware', async (req, res, next) => {
  try {
    // You can calculate "success" variable based on your custom logic
    if(success){
      await send_email_message('example@gmail.com', 'Success', 'This is body of success message.');
      return res.status(200).json({ success: true });
    } else {
      await send_email_message('example@gmail.com', 'Error', 'This is body of error message.');
      return res.status(400).json({ success: false });
    }
  } catch(error) {
    return res.status(400).json({ success: false });
  }
});

module.exports = router;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda