You need to enable JavaScript to run this app. 如何通过Nodemailer发送Firebase Storage获取的文件作为邮件附件
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Nodemailer发送Firebase Storage获取的文件作为邮件附件

代码调整方案

你需要针对以下几个核心问题修改代码:

  • 修正Nodemailer配置错误:附件配置字段是复数attachments,不是你写的单数attachment
  • 调整异步逻辑写法:Firebase Realtime Database的once方法支持Promise调用,不要用回调嵌套,同时云函数必须正确返回Promise,避免执行被提前中断
  • 新增存储文件读取逻辑:将触发事件对应的存储桶文件下载为Buffer,作为附件内容传入发送邮件方法
  • 修复语法错误:原代码末尾多了一个多余的闭合大括号
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
admin.initializeApp(); // 如果你之前已经完成admin初始化可以省略这行

const transport = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
    user: "xxxxxxxxxx@gmail.com",
    pass: "xxxxxxxxxxxxxxx"
  }
});

exports.sendConfirmationEmail = functions.storage.bucket('bucket-name').object().onFinalize(async (object) => {
  try {
    const orderID = object.name.slice(0, -4);
    // 读取订单数据
    const snapshot = await admin.database().ref('/pedidos/' + orderID).once('value');
    const orderData = snapshot.val();
    if (!orderData) return null;

    // 下载存储桶中的文件为Buffer
    const bucket = admin.storage().bucket(object.bucket);
    const file = bucket.file(object.name);
    const [fileBuffer] = await file.download();
    const [fileMetadata] = await file.getMetadata();

    // 构造Nodemailer要求的附件格式
    const emailAttachment = {
      filename: object.name,
      content: fileBuffer,
      contentType: fileMetadata.contentType
    };

    // 触发邮件发送
    return await sendEmail(orderData.customer, orderData.email, orderData.number, emailAttachment);
  } catch (e) {
    console.error("触发器执行错误:", e);
    return null;
  }
});

function sendEmail(user, email, order, file){
  console.log("Sending Email...");
  return transport.sendMail({
      from: "XXXXXX <xxxxxxxxxx@gmail.com>",
      to: email,
      subject: "Confirmación pedido " + order,
      html: `
            <h1> Estiamdo ${user}, </h1>
            <p> Hemos recibido su pedido correctamente. Le mantendremos infromado de su estado. </p>
            <p> Gracias por confiar en nosotros </p>
          `,
      attachments: [file] // 修正为复数字段,支持传入多个附件
    })
    .then(r => r)
    .catch(e => {
      console.log("An error has ocurred " + e);
    });
}

注意:如果你使用Gmail作为发件邮箱,现在已经不支持直接使用账号密码登录SMTP服务,需要先开启账号的两步验证,然后生成应用密码填入auth.pass字段使用。

内容的提问来源于stack exchange,提问作者martibellot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 07:24:04