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

使用Nodemailer接收用户邮件异常:发件人显示不符问题求助

问题描述

我尝试使用Nodemailer接收用户发送的邮件,预期由用户邮箱发件、我的邮箱收件,但设置不同邮箱为from和to参数后,实际仍是我的邮箱给自己发件。不过当将from设为我的邮箱、to设为用户邮箱时,发送功能却能正常运行。请问这是什么原因?该如何修复才能实现接收用户邮件的需求?

我的代码

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    service: "gmail",
    secure: false,
    auth: {
        user: process.env.MY_EMAIL,
        pass: process.env.MY_PASSWORD,
    },
});

// Creating the email
let info = {
    from: process.env.USERS_EMAIL,
    to: process.env.MY_EMAIL,
    subject: 'Demo message',
    text: 'For clients with plaintext support only',
    html: `
    <p>This is a demo email</p>
`
};
//send the email
transporter.sendMail(info, function (err, info) {
    if (err) {
        console.log(err);
    }
    else{
        console.log(info);
    }
})
原因分析
  • 你用的是自己的Gmail SMTP服务器发邮件,Gmail的安全机制会强制把from字段替换成你认证的邮箱(也就是process.env.MY_EMAIL),不允许伪造发件人,所以实际发件人还是你的邮箱。
  • 核心逻辑错误:Nodemailer是发送邮件的工具,不是接收邮件的工具。你现在的代码是在发邮件,不是收用户主动发给你的邮件。
解决方案

分两种场景处理:

场景1:真正接收用户主动发送到你邮箱的邮件

需要用IMAP/POP3协议读取你的收件箱,步骤如下:

  • 开启你邮箱的IMAP功能(以Gmail为例,在设置里开启“IMAP访问”)。
  • 如果Gmail开启了两步验证,需要生成应用专用密码,代替原密码使用。
  • 使用imap或nodemailer-imap这类库,编写代码定时检查收件箱,获取用户发来的邮件。

场景2:让用户通过你的应用提交内容,再以“用户名义”发邮件给你

这种情况不能直接用用户邮箱当发件人(你没有用户邮箱的SMTP权限),正确做法是:

  • 发件人from必须用你认证的邮箱。
  • 添加replyTo字段为用户邮箱,方便你直接回复用户。
  • 在邮件主题或正文里明确标注用户的邮箱和提交内容。

修正后的代码示例

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    service: "gmail",
    secure: true, // 建议开启secure,使用465端口更安全
    auth: {
        user: process.env.MY_EMAIL,
        pass: process.env.MY_PASSWORD, // Gmail开启两步验证的话,这里填应用专用密码
    },
});

// 修正后的邮件配置
let info = {
    from: process.env.MY_EMAIL, // 必须用认证邮箱作为发件人
    to: process.env.MY_EMAIL,
    replyTo: process.env.USERS_EMAIL, // 设置用户邮箱,回复时自动指向用户
    subject: `来自${process.env.USERS_EMAIL}的消息`,
    text: `用户邮箱:${process.env.USERS_EMAIL}\n消息内容:For clients with plaintext support only`,
    html: `
    <p>用户邮箱:${process.env.USERS_EMAIL}</p>
    <p>This is a demo email</p>
`
};

// 发送邮件
transporter.sendMail(info, function (err, info) {
    if (err) {
        console.log(err);
    } else {
        console.log(info);
    }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:40:27