Zoro Raka
Zoro Raka

Reputation: 487

How to Sendmail Using NodeMailer (Not SMTP) With Promise (Bluebird)?

How to sendmail using nodemailer + bluebird (Promise). I successfully send to Email, but not response for it (in the page it still loading and doesn't response anything, but it succeeds in sending to email).

This is file js :

    return new Promise(resolve => {
    var transporter = nodemailer.createTransport({
        sendmail: true,
        newline: "windows",
        logger: false
      }),
      message = {
        from: "[email protected]",
        to: variabletoemail,
        subject: variablesubject,
        html: variablesendhtml
      };
    transporter.sendMail(message, (error, response) => {
      if (error) {
        resolve("0"); //can't call
      } else {
        resolve("1"); //can't call
      }
    });
  });

Does anyone know my problem above. Please help me

Upvotes: 1

Views: 314

Answers (1)

Ramin Rezazadeh
Ramin Rezazadeh

Reputation: 336

Base on documentation, send mail return promise and you can not use it with callback passing. You can use it with await and use try catch to resolve or reject your promise.

return new Promise(async (resolve, reject) => {
    var transporter = nodemailer.createTransport({
        sendmail: true,
        newline: "windows",
        logger: false
      }),
      message = {
        from: "[email protected]",
        to: variabletoemail,
        subject: variablesubject,
        html: variablesendhtml
      };
    try{
      await transporter.sendMail(message);
      resolve("1")
    }catch(e){
      reject(e)
    }
  });

or without try catch:

return new Promise((resolve, reject) => {
        var transporter = nodemailer.createTransport({
            sendmail: true,
            newline: "windows",
            logger: false
          }),
          message = {
            from: "[email protected]",
            to: variabletoemail,
            subject: variablesubject,
            html: variablesendhtml
          };
          transporter.sendMail(message).then(()=>{
           resolve("1")
          }).catch((e) => {
           reject(e)
          });
      });

Upvotes: 2

Related Questions