Unable to send Email using nodemailer in protractor.conf.js onComplete: function()

元气小坏坏 提交于 2019-12-24 09:31:54

问题


Unable to send Email using nodemailer in protractor.conf.js onComplete: function(). Used the below code and it does not execute onComplete block

onComplete: function() {    
    var nodemailer = require('nodemailer');
    var transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true, // use SSL
        auth: {
            user: 'email',
            pass: 'password'
        }
    });
    var mailOptions = {
            from: '"TestMail" <>', // sender address (who sends)
            to: 'receiver's email', // list of receivers (who receives)
            subject: 'Hello through conf', // Subject line
            text: 'Hello world ', // plaintext body
            html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js', // html body


    };

        transporter.sendMail(mailOptions, function(error, info){
            if(error){
                return console.log(error);
            }

            console.log('Message sent: ' + info.response);
        });

回答1:


You need to return a Promise. Only then onComplete() would wait till the Promise is resolved - mail is triggered.

A callback function called once tests are finished. onComplete can
optionally return a promise, which Protractor will wait for before
shutting down webdriver. At this point, tests will be done but global objects will still be available. onComplete?: () => void

You need to convert your function to return a Promise once an email is trigerred successfully. Refer this beautiful tutorial. They have a very good example on converting a fs.readFile() to return a promise

You can do something like this.

onComplete: function() {
    return new Promise(function (fulfill, reject){
        var transporter = nodemailer.createTransport({
            host: 'smtp.gmail.com',
            port: 465,
            secure: true, // use SSL
            auth: {
                user: 'email',
                pass: 'password'
            }
        });
        var mailOptions = {
            from: '"TestMail" <>', // sender address (who sends)
            to: 'receiver's email', // list of receivers (who receives)
            subject: 'Hello through conf', // Subject line
            text: 'Hello world ', // plaintext body
            html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js', // html body
    };
        transporter.sendMail(mailOptions, function(error, info){
            if(error){
                reject(err);
            }
            fulfill(info);
        });
    });
}


来源:https://stackoverflow.com/questions/42970772/unable-to-send-email-using-nodemailer-in-protractor-conf-js-oncomplete-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!