【发布时间】:2019-05-22 21:26:25
【问题描述】:
我正在尝试使用通过 nodemailer 上传到我的 firebase 项目存储 (appId.appspot.com/templates/testTemplate.hbs) 的车把模板文件,以便在实时数据库节点上触发 onCreate 函数时发送电子邮件。
我可以使用 html 格式的字符串成功发送电子邮件,但确实需要使用模板将动态数据添加到电子邮件中。
这是我的功能:
import * as functions from "firebase-functions";
const admin = require("firebase-admin");
const hbs = require("nodemailer-express-handlebars");
const nodemailer = require("nodemailer");
const smtpConfig = {
host: "mailHost",
port: 465,
secure: true,
auth: {
user: "xxxxxxxx",
pass: "xxxxxxxx"
}
};
const transporter = nodemailer.createTransport(smtpConfig);
exports.sendEmail = functions.database
.ref("/databasePath/{pushId}")
.onCreate(async (snapshot, context) => {
const userData = snapshot.val();
admin.initializeApp({
storageBucket: "appId.appspot.com"
});
const bucket = admin.storage().bucket();
const templatesFolder = bucket.name + "/templates/"; // path to storage folder with templates
transporter.use(
"compile",
hbs({
viewPath: templatesFolder,
extName: ".hbs"
})
);
const uniqueCode = "generated by a function";
const uniqueLink = "https://appId.firebaseapp.com/?id=" + uniqueCode;
const message = {
from: "fromEmail",
to: "toEmail",
subject: "Subject",
template: "testTemplate", // name of the template file
context: {
user: "User name",
link: uniqueLink
}
};
try {
await transporter.sendMail(message);
console.log("Email sent to:", "toEmail");
} catch (error) {
console.error("Error sending email:", error);
}
return null;
});
触发该功能时,我在日志中收到以下错误:
发送电子邮件时出错:{ 错误:ENOENT:没有这样的文件或目录,打开 '/user_code/appId.appspot.com/templates/testTemplate.hbs' 在错误(本机) 错误号:-2, 代码:'ENOENT', 系统调用:'打开', 路径:'/user_code/appId.appspot.com/templates/testTemplate.hbs' }
bucket.name 开头有“/user_code”,因此 hbs 找不到模板。如何获得模板文件夹的正确路径?
【问题讨论】:
标签: firebase firebase-realtime-database firebase-authentication google-cloud-functions nodemailer