【问题标题】:Creating custom email template for nodemailer in firebase cloud functions?在firebase云功能中为nodemailer创建自定义电子邮件模板?
【发布时间】:2021-01-08 12:34:53
【问题描述】:

任何人都可以就如何创建与 Firebase 云功能一起使用的动态电子邮件模板进行权衡吗? 基本上,我创建了一个函数,该函数将在到达/sendEmail 端点时被调用。它在req 正文中保存数据,我正在检索该数据并使用nodemailer 通过电子邮件发送。

如果我想使用 handlebars 创建模板,我会遇到路径错误。错误是no such file or directory exists。我尝试了两个不同的路径,第一个在functions/src/email/template.html 下,第二个与functions文件夹处于同一级别。

发送邮件功能

const transporter = nodemailer.createTransport({
            service: 'gmail',
            auth: {
                user: 'example@gmail.com',
                pass: 'dqsdsqdqsdsq'
            }
        });
        const filePath = path.join(__dirname, 'functions/src/Email/template.html');
        const source = fs.readFileSync(filePath, 'utf-8').toString();
        const template = handlebars.compile(source);
        const replacements = {
            schoolName: schoolName,
            className: className,
            date: new Date(),
            responsibiltyId: responsibiltyId,
            memorialId: memorialId
        };
        const htmlToSend = template(replacements);
        const mailOptions = {
            from: 'ADMIN <example@gmail.com>', // Something like: Jane Doe <janedoe@gmail.com>
            to: destination,
            subject: `Session Codes for Class ${className} | ${schoolName} | ${new Date()}`, // email subject
            html: htmlToSend
        };
        return transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return handleError(res, error);
            }
            return res.status(200).json({
                timestamp: new Date(),
                status: 200,
                message: `Email has been sent successfuly to ${destination}`,
                extra: ''
            });
        });
    

【问题讨论】:

  • console.log(__dirname) 打印出什么? path.join() 将加入 __dirname 和 functions/src/Email/template.html./ 你能再次确认 __dirname 和加入的路径吗?
  • 我正在尝试做的事情似乎有些牵强,所以我必须在正常的 .ts 之前在 nodemailer 中创建一个 html 部分,然后将其分配给 html 选项:/
  • 你确认路径了吗?
  • 替换下面一行 const filePath = path.join(__dirname, 'functions/src/Email/template.html'); with const filePath = path.join('', 'src/Email/template.html');

标签: node.js google-cloud-functions handlebars.js nodemailer


【解决方案1】:

部署函数时,函数文件夹中的所有内容都会打包并发送到 Cloud Functions。该文件夹之外的任何内容都不会发送,这意味着您的 template.html 文件夹在运行时不可用。如果您希望部署的代码在运行时可以读取内容,则在运行部署命令之前,它应该位于 functions 文件夹中。

【讨论】:

    【解决方案2】:

    替换这行代码

    const filePath = path.join(__dirname, 'functions/src/Email/template.html');
    

    const filePath = path.join('', 'src/Email/template.html');
    

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 2018-11-15
      相关资源
      最近更新 更多