5

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
fanhats
  • 777
  • 2
  • 10
  • 20
  • 1
    You're not showing us your whole code - please make a version that reproduces it - also - at what line is the unhandled rejection error at? (The fact you're getting this message indicates that bluebird _does_ see the error. – Benjamin Gruenbaum Jun 20 '15 at 12:00
  • same issue with couchbase crud methods. – Reza Owliaei Dec 13 '15 at 15:07

6 Answers6

3

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)
            });
        });
    }
}
mido
  • 24,198
  • 15
  • 92
  • 117
Juho
  • 427
  • 2
  • 12
1

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);
            }
        });
    });
};
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
0

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.

naartjie
  • 1,505
  • 1
  • 9
  • 18
0

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

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: '1@test.com',
    to: '2@test.com',
    text: 'Hello world!',
    subject: 'Test'
})

console.log(promise)

This log above will return Promise { <pending> }

João Pedro
  • 1
  • 1
  • 1
0

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 
  }
 
Chen Peleg
  • 953
  • 10
  • 16