Promisify Nodemailer with bluebird?

3k Views Asked by At

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?

6

There are 6 best solutions below

0
On

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)
            });
        });
    }
}
0
On

This worked for me (node 10.9, 2022):

  const sendEmail = async () => {
    const transport = nodemailer.createTransport(transportOptions);
    const transportAsPromise = Promise.promisify(transport.sendMail, { 
    context: transport, multiArgs: true });
    const sendResult = await transportAsPromise(emailDataToSend);
    ...
    return sendResult 
  }
 
2
On

Now if you just omit the callback it returns a promise.

Example

const nodemailer = require('nodemailer')

const transport = nodemailer.createTransport({
    host: 'smtp_host',
    port: 'smpt_port',
    auth: {
        user: 'smpt_auth_user',
        pass: 'smpt_auth_password',
    },
})

const promise = transport.sendMail({
    from: '[email protected]',
    to: '[email protected]',
    text: 'Hello world!',
    subject: 'Test'
})

console.log(promise)

This log above will return Promise { <pending> }

0
On

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.

0
On

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);
            }
        });
    });
};
0
On

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.