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

使用Nodemailer从表单发邮件出现收件人未定义错误求助

问题解决:表单提交邮箱字段未被服务端识别,Nodemailer提示无收件人

核心问题分析

  • 服务端语法错误:mailOptions中from字段后缺少逗号,导致JS语法错误,直接中断邮件发送逻辑
  • 请求格式不匹配:客户端用FormData发送multipart/form-data格式请求,但服务端仅配置了bodyParser.urlencoded,无法解析该格式,导致req.body无法正确获取邮箱字段
  • 重复绑定事件风险:表单提交事件绑定在goFlower4函数内,若函数多次执行会重复绑定事件,可能引发多次请求或异常行为

分步解决方案

1. 修复服务端语法错误

打开app.js,在mailOptions的from字段后添加逗号:

// Email content
const mailOptions = {
    from: 'myemail@gmail.com', // 新增逗号修复语法错误
    to: email,
    subject: 'Happy Birthday!',
    text: "Your days have grown weary and your purpose on this planet is unclear. At 33, the time has come. Click here to reveal all the answers you've been waiting for."
};

2. 调整服务端解析中间件以支持FormData

安装multer中间件用于解析multipart/form-data格式:

npm install multer

在app.js中引入并配置:

const express = require('express');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const cors = require('cors');
const multer = require('multer'); // 新增
const upload = multer(); // 新增,无磁盘存储配置
const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.none()); // 新增,解析非文件类型的FormData字段

// Allow requests from a specific origin
app.use(cors({
  origin: 'http://127.0.0.1:5500'
}));

// 其余代码保持不变

3. 避免重复绑定表单提交事件

将submit事件绑定移到goFlower4函数外,确保仅绑定一次:

// 页面加载时绑定一次提交事件
form.addEventListener('submit', function(event) {
    event.preventDefault();

    const formData = new FormData(this);

    fetch('http://localhost:3000/send-email', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => {
        console.log(data); 
        if (data === 'Email sent successfully') {
            console.log('Email sent successfully');
        } else {
            console.error('Error: Something went wrong');
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
});

function goFlower4() {
    update(locations[2]);
    for (let button of responseButtons) {
        button.style.display = "none";
    }
    form.style.display = 'inline-block';
}

4. 清理HTML表单冗余属性

移除form标签上空的name属性,避免潜在干扰:

<form id="form" action="/send-email" method="post">
    <label for="email">My email address is </label>
    <input type="email" id="email" name="email" autocomplete="on" required>
    <button type="submit" id="submit">send</button>
</form>

验证步骤

  1. 重启Node.js服务
  2. 测试表单提交,查看浏览器网络面板确认email字段正确发送
  3. 检查服务端控制台,确认Recipient Email输出正确的邮箱地址
  4. 验证邮件是否成功发送

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:24:57