0

Trying to connect works but then an E-Mail is never sent and also no exceptions or anything are thrown. As you can see I tried to add a message to my response (error1, success1, error2, success2) to narrow down where I might fail, but the messages are also not set.

This is my transporter:

const transporter = nodemailer.createTransport({
  host: "my.host.com",
  port: 996,
  secure: true,
  auth: {
    user: "myuser@email.com",
    pass: "mypassword",
  },
});

then the following code is inside a post request function. the rest of the function works fine, so no problems with the endpoint or anything like that.

let mailOptions = {
    from: "me@mail.com",
    to: "you@mail.com",
    subject: "Test mail",
    text: "It's working",
  };
  // verify connection configuration
  let error1 = "nope";
  let success1 = "nope";
  let error2 = "nope";
  let success2 = "nope";

  try {
    transporter.verify();    
    success1 = "Server is ready to take messages";
  } catch (err) {
    error1 = "connection error";
    const error = new HttpError(`connection error: ${err}`, 500);
    return next(error);
  }

  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      error2 = `Error on sending mail: ${error}`;
    } else {
      success2 = `Mail sent: ${info.response}`;
    }
  });

  res.status(201).json({
    error1: error1,
    success1: success1,
    error2: error2,
    success2: success2,
  });

and this is the response i get after submitting:

error1: "nope",error2: "nope",success1: "Server is ready to take messages",success2: "nope"

error2 or success2 should have a message as well. What am I missing?

Melvin
  • 329
  • 4
  • 20
  • 1
    Node is asynchronous. res.status runs before transporter.sendmail has executed. Move the res.status to the callback of sendmail. – Brahma Dev Jun 17 '21 at 12:42
  • 1
    I believe this has something to do with the asynchronous behavior of `transporter.sendMail()`, because your `res.status()` might be getting executed before `transporter.sendMail()` has completed execution – me.nkr Jun 17 '21 at 12:45
  • @BrahmaDev Thanks so much, this solved it for me. Do you want to add your comment as an answer so I can accept it? – Melvin Jun 17 '21 at 13:08

0 Answers0