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

Node.js环境下使用Nodemailer加密邮件正文的技术咨询

Node.js + Nodemailer 邮件正文加密方案

首先明确:你提供的邮件内容里的Content-Transfer-Encoding: base64是编码而非加密,仅用于将二进制内容转为文本格式方便传输,不具备保密能力。要实现邮件正文的真正加密,需要采用端到端加密方案,以下是具体实现细节:

1. 加密方式名称:OpenPGP

这是当前邮件端到端加密的主流标准,基于PGP(Pretty Good Privacy)协议的开源实现,能确保只有持有对应私钥的收件人才能解密内容,中间服务商(如邮件服务器)无法读取邮件正文。

2. 适用的Node.js库

  • openpgp:官方维护的OpenPGP协议完整实现,支持加密、解密、签名、验证等全流程操作,社区活跃,文档完善。
  • pgp-encrypt-mail:针对邮件场景封装的轻量工具库,API更简洁,但功能覆盖不如openpgp全面。

3. 结合Nodemailer的实现步骤

以openpgp库为例,给出可直接运行的代码示例:

安装依赖

npm install nodemailer openpgp

加密发送逻辑

const nodemailer = require('nodemailer');
const openpgp = require('openpgp');

// 提前获取收件人的OpenPGP公钥(需从收件人处获取)
const recipientPublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK-----
// 替换为收件人的实际公钥内容
-----END PGP PUBLIC KEY BLOCK-----`;

// 加密邮件正文的工具函数
async function encryptContent(rawContent) {
  const publicKey = await openpgp.readKey({ armoredKey: recipientPublicKey });
  const encryptedMsg = await openpgp.encrypt({
    message: await openpgp.createMessage({ text: rawContent }),
    encryptionKeys: publicKey
  });
  return encryptedMsg;
}

// 发送加密邮件
async function sendEncryptedMail() {
  // 配置Nodemailer传输器(替换为你的SMTP服务信息)
  const transporter = nodemailer.createTransport({
    host: 'smtp.your-domain.com',
    port: 465,
    secure: true,
    auth: {
      user: 'your-account@your-domain.com',
      pass: 'your-password'
    }
  });

  // 原始邮件正文(支持HTML或纯文本)
  const rawHtml = '<h1>机密邮件</h1><p>这是需要加密的敏感内容</p>';
  
  // 加密正文
  const encryptedContent = await encryptContent(rawHtml);

  // 发送邮件:加密内容作为纯文本发送,同时在HTML中提示收件人解密
  const sendResult = await transporter.sendMail({
    from: 'your-account@your-domain.com',
    to: 'recipient@example.com',
    subject: '[加密] 机密内容通知',
    text: encryptedContent,
    html: `<div>
            <p>这是一封OpenPGP加密邮件,请使用私钥解密以下内容:</p>
            <pre style="background:#f5f5f5; padding:10px;">${encryptedContent}</pre>
          </div>`
  });

  console.log('加密邮件已发送,消息ID:', sendResult.messageId);
}

// 执行发送
sendEncryptedMail().catch(err => console.error('发送失败:', err));

关键注意事项

  • 必须预先获取收件人的OpenPGP公钥,公钥用于加密,只有对应的私钥才能解密内容。
  • 收件人需要使用支持OpenPGP的工具(如Thunderbird+Enigmail、GPG Suite)或邮件客户端来解密邮件。
  • 如需同时验证发件人身份,可在加密时加入自己的私钥进行签名,收件人用你的公钥验证签名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:18:14