简体   繁体   中英

Promisify Nodemailer with bluebird?

The nodemailer author has made clear he's not supporting promises. I thought I'd try my hand at using bluebird, but my attempt at it doesn't seem to catch any errors that Nodemailer throws:

var nodemailer = require('nodemailer');
var Promise = require('bluebird');

// build the transport with promises
var transport = Promise.promisifyAll( nodemailer.createTransport({...}) );

module.exports = {
    doit = function() {
        // Use bluebird Async
        return transport.sendMailAsync({...});
    }
}

Then I call it by doing:

doit().then(function() {
    console.log("success!");
}).catch(function(err) {
    console.log("There has been an error");
});

However, when providing an invalid email, I see this:

Unhandled rejection Error: Can't send mail - all recipients were rejected

So, the nodemailer error isn't being caught by my bluebird promise. What have I done wrong?

Can't say what's wrong with the code from the top of my head. I've ran into similar problems with promisification and decided it's easier to just promisify the problem cases manually instead. It's not the most elegant solution, but it's a solution.

var transport = nodemailer.createTransport({...});

module.exports = {
    doit: function() {
        return new Promise(function (res, rej) {
           transport.sendMail({...}, function cb(err, data) {
                if(err) rej(err)
                else res(data)
            });
        });
    }
}

This how I got it working (typescript, bluebird's Promise, nodemailer-smtp-transport):

export const SendEmail = (from:string,
                          to:string[],
                          subject:string,
                          text:string,
                          html:string) => {

    const transportOptions = smtpConfiguration; // Defined elsewhere

    const transporter = nodemailer.createTransport(smtpTransport(transportOptions));

    const emailOptions = {
        from: from,
        to: to.join(','),
        subject: subject,
        text: text,
        html: html
    };

    return new Promise((resolve, reject) => {
        transporter.sendMail(emailOptions, (err, data) => {
            if (err) {
                return reject(err);
            } else {
                return resolve(data);
            }
        });
    });
};

You could try with the on-the-fly Promise creation with .fromNode() ?

var nodemailer = require('nodemailer');
var Promise = require('bluebird');

module.exports = {
    doit = function() {            
        return Promise.fromNode(function(callback) {
            transport.sendMail({...}), callback);
        }
    }
}

doit() will return a bluebird promise. You can find the docs for .fromNode() here .

If you just want Promisify the .sendMail method, you can do like this:

const transport = nodemailer.createTransport({
  host: mailConfig.host,
  port: mailConfig.port,
  secure: true,
  auth: {
    user: mailConfig.username,
    pass: mailConfig.password,
  },
});

const sendMail = Promise.promisify(transport.sendMail, { context: transport });

And using it like this:

const mailOptions = {
  from: ...,
  to: ...,
  subject: ...,
  html: ...,
  text: ...,
};

sendMail(mailOptions)
  .then(..)
  .catch(..);

Or if you using async/await wrapped in async function:

./mail.js

const send = async (options) => {
  ...

  return sendMail(options);
};

export default { send };

And await when you using it

./testing.js

import mail from './mail';

await mail.sendMail(options);

You get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM