Search code examples
node.jsemailibm-cloudopenwhisk

Sending a mail via NODE.JS in an IBM Cloud function


I have similar problem as here: PHP mail function doesn't complete sending of e-mail But after several tries I don't think it's my solution...

Objective: Create an action which can send email. Code:

function main(params) {
const params = {
    "payload": {
       "id": "[email protected]",
       "password": "CodeForTheSenderAccount",
       "receiver": "[email protected]",
       "subject": "Test Wikit",
       "body": "<html>HELLO WORLD</html>"
    }
}
const nodemailer = require('nodemailer');
//Creation of a SMTP transporter
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: params.payload.id,
        pass: params.payload.password
    }
});
//Creation of data to send
const mail = {
    from: '"Wikitest" <' + params.payload.id + '>',
    to: params.payload.receiver,
    subject: params.payload.subject,
    text: 'Hello World',
    html: params.payload.body
}
//Sending the mail
return(transporter.sendMail(mail, function (err, info) {
    if (err) {
        const ret = {status: 'OK'};
    } else {
        const ret = {status: 'KO'};
    }
    transporter.close();
    return (ret);
}));
}

This code works locally and I receive the email. But not when running the function in the IBM Cloud console.

I think it's due to SMTP servers but I'm not sure...

Some of you will see the "payload" param. It's because this action is in a sequence and the action before send the params.


Solution

  • When working with asynchronous JavaScript in serverless functions, you need to return and resolve a Promise. Here is relevant documentation for your example https://github.com/apache/incubator-openwhisk/blob/master/docs/actions-node.md#creating-asynchronous-actions.

    return(new Promise(function(resolve, reject) {
      transporter.sendMail(mail, function (err, info) {
        if (err) {
            const ret = {status: 'OK'};
        } else {
            const ret = {status: 'KO'};
        }
      transporter.close();
      resolve(ret);
    }}));