简体   繁体   English

用蓝鸟宣传Nodemailer?

[英]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: 我以为我会尝试使用蓝鸟,但我尝试它似乎没有发现Nodemailer抛出的任何错误:

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. 因此,我的蓝鸟承诺没有捕获到nodemailer错误。 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. 我遇到了与promisification类似的问题,并决定手动宣传问题案例更容易。 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): 这是我如何工作(打字稿,蓝鸟的承诺,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() ? 您可以尝试使用.fromNode()创建即时Promise吗?

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. doit()将返回蓝鸟承诺。 You can find the docs for .fromNode() here . 你可以在这里找到.fromNode()的文档。

If you just want Promisify the .sendMail method, you can do like this: 如果你只想要Promisify .sendMail方法,你可以这样做:

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: 或者如果您使用async/await包装在异步函数中:

./mail.js

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

  return sendMail(options);
};

export default { send };

And await when you using it await你使用它

./testing.js

import mail from './mail';

await mail.sendMail(options);

You get the idea. 你明白了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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