You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter调用Firebase云函数传递数据时,email始终显示undefined导致邮件发送失败

Flutter调用Firebase云函数传递数据时,email始终显示undefined导致邮件发送失败

我仔细检查了你的Firebase云函数代码,发现问题根源在于代码结构存在严重的语法错误和逻辑混乱,导致无法正确解析Flutter端传递过来的payload参数,最终出现email=undefined的错误。

核心问题分析

从你的代码里能看到几个致命错误:

  1. 重复定义云函数:在主sendInvitationEmail函数内部,你又重新赋值了exports.sendInvitationEmail,这会直接打乱代码执行逻辑,后续的payload解析步骤根本无法按预期运行。
  2. 冗余且混乱的变量声明:重复声明const payload,还出现了未定义的unwrapPayload函数调用(代码里没看到这个函数的实现),进一步破坏了参数解析流程。
  3. 逻辑执行顺序错误:嵌套的函数定义导致主函数的后续代码虽然有日志输出,但实际参数解析已经因为前面的错误而失效。

而Flutter端的日志显示你传递的payload是完全正确的:{email: shalqlq@mail.bg, code: c84ba520-0f82-4215-892f-25338584a8bb, ...},所以问题100%出在云函数端的代码结构上。

修正后的完整云函数代码

下面是修复后的代码,我清理了所有错误结构,确保逻辑正确:

const functions = require("firebase-functions");
const nodemailer = require("nodemailer");

// 初始化邮件传输器(原代码缺失这部分,必须补充)
const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: "vaninka777@gmail.com",
    pass: "你的Gmail应用专用密码" // 注意:不要用邮箱登录密码,需启用Gmail应用专用密码
  }
});

exports.sendInvitationEmail = functions.https.onCall(async (data, context) => {
  // 1. 打印原始传入数据,用于调试
  console.log("📥 原始传入数据:", data);

  // 2. 直接使用Flutter端传递的data作为payload
  const payload = data;
  console.log("📦 解析后的Payload:", payload);

  // 3. 解构获取参数
  const { email, code, companyName, role } = payload;
  console.log("📧 Email:", email);
  console.log("🔐 Code:", code);
  console.log("🏢 Company:", companyName);
  console.log("🎭 Role:", role);

  // 4. 严格验证email参数
  if (!email || typeof email !== 'string' || !email.includes('@')) {
    console.error("❌ 无效/空邮箱:", email);
    throw new functions.https.HttpsError('invalid-argument', 'Invalid e-mail');
  }

  // 5. 配置邮件选项
  const mailOptions = {
    from: '"我的应用名称" <vaninka777@gmail.com>',
    to: email,
    subject: `邀请加入${companyName}`,
    text: `你的注册码是:${code},你的角色是${role}`,
    // 如果需要HTML格式邮件,可添加html字段:
    // html: `<p>你的注册码是:<strong>${code}</strong></p><p>角色:${role}</p>`
  };

  try {
    console.log('📤 准备发送邮件到:', email);
    await transporter.sendMail(mailOptions);
    console.log("✅ 邮件发送成功");
    return { success: true };
  } catch (error) {
    console.error("❗ 邮件发送失败:", error);
    throw new functions.https.HttpsError("unknown", "邮件发送失败,请稍后重试");
  }
});

关键修改点说明

  1. 移除重复函数定义:彻底删除了主函数内部嵌套的exports.sendInvitationEmail声明,确保代码逻辑线性执行。
  2. 清理冗余代码:去掉了无效的unwrapPayload调用(Flutter端已直接传递键值对,无需额外解析),统一使用传入的data作为payload。
  3. 补充邮件传输器初始化:原代码缺失发送邮件的核心配置,补充了transporter的初始化(注意Gmail的权限配置)。
  4. 规范验证逻辑:保留了严格的email格式验证,确保参数合法才继续执行。

后续测试建议

  1. 部署修正后的云函数:执行firebase deploy --only functions命令部署更新。
  2. 重新测试Flutter端调用:调用后查看Firebase控制台的函数日志,确认📧 Email:日志能正确显示传入的邮箱地址。
  3. 检查邮件权限:确保Gmail账号开启了SMTP服务,并且使用应用专用密码(避免登录限制和安全风险)。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 10:14:33