我正在尝试利用nodemailer和firebase云功能构建一个mailer函数:
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport("smtps://gmailEmail:gmailPassword@smtp.gmail.com");
const test = 'some.email@gmail.com'
const APP_NAME = 'Dati fatturazione elettronica';
exports.sendDatas = functions.database.ref('/datiFatt/{pushId}').onCreate((data) => {
console.log(data);
const name = data.name;
const pec = data.pec
const id = data.id;
return sendEmail(name, pec, id);
});
function sendEmail(name, pec, id) {
const mailOptions = {
from: `${gmailEmail}`,
to: test
};
mailOptions.subject = `Data from ${name}!`;
mailOptions.html = `${name} \n ${pec} \n ${id} `;
return mailTransport.sendMail(mailOptions)
.then(() => {
return console.log('New email sent to:', test);
});
}
但是以某种方式,此函数在其所有字段中都返回“ undefined”。 可能是我以错误的方式访问数据。
答案 0 :(得分:1)
您的sendEmail
函数可能是错误的。您正在尝试return console.log
。
尝试调整为以下格式;
function sendEmail(name, pec, id) {
const mailOptions = {
from: `${gmailEmail}`,
to: test
};
mailOptions.subject = `Data from ${name}!`;
mailOptions.html = `${name} \n ${pec} \n ${id} `;
return mailTransport.sendMail(mailOptions)
.then(() => {
console.log('New email sent to:', test);
return;
});
}
答案 1 :(得分:1)
您应在代码中纠正两个地方:
首先,因为您似乎正在使用Firebase SDK for Cloud Functions的旧版本(即val()
的DataSnapshot
方法(在您的情况下为data.data
)访问数据库,如下所示:
exports.sendDatas = functions.database.ref('/datiFatt/{pushId}').onCreate((data) => {
const name = data.data.val().name;
const pec = data.data.val().pec
const id = data.data.val().id;
....
});
请注意,将回调函数的参数命名为event
而不是data
更加明显,并修改如下代码:
exports.sendDatas = functions.database.ref('/datiFatt/{pushId}').onCreate((event) => {
const name = event.data.val().name;
....
});
但是,我建议您升级到SDK的最新版本,并因此使用最新的语法({....onCreate((snap, context) => {const name = snap.val().name; ....});
请参见上面引用的doc)。
其次,对于由实时数据库中的事件触发的云功能(如其他后台功能),您必须返回一个Promise,以在功能完成(或生成错误)时向平台指示。因此,您应该修改功能,如下所示:
function sendEmail(name, pec, id) {
const mailOptions = {
from: `${gmailEmail}`,
to: test
};
mailOptions.subject = `Data from ${name}!`;
mailOptions.html = `${name} \n ${pec} \n ${id} `;
return mailTransport.sendMail(mailOptions);
});
}