在 IBM Cloud 函数中通过 NODE.JS 发送邮件

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

我遇到了与此处类似的问题:PHP mail function doesn't complete sending of e-mail 但是经过几次尝试,我认为这不是我的解决方案...

Objective: 创建一个可以发送电子邮件的操作。 代码:

function main(params) {
const params = {
    "payload": {
       "id": "sender.address@gmail.com",
       "password": "CodeForTheSenderAccount",
       "receiver": "another.mail.address@gmail.com",
       "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);
}));
}

此代码在本地有效,我收到了电子邮件。但当 运行 IBM Cloud 控制台中的函数时不是。

我认为这是因为 SMTP 服务器,但我不确定...

有些人会看到 "payload" 参数。因为这个action是在sequence中的,而且是发送参数之前的action。

在无服务器函数中使用异步 JavaScript 时,您需要 return 并解析 Promise。这是您的示例的相关文档 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);
}}));