Nodemailer nodemailer

Nodemailer 是一个功能强大的 Node.js 邮件发送模块,专为后端开发人员设计,用于实现自动化邮件通知系统。它支持 SMTP、OAuth2 等多种认证方式,能够发送包含 HTML 模板、附件和内嵌图片的专业邮件。适用于用户注册验证、密码重置、交易通知、营销推广、系统告警等场景,是构建可靠邮件通信服务的核心工具。关键词:Node.js邮件发送、SMTP客户端、邮件自动化、HTML邮件模板、OAuth2认证、附件发送、后端通知系统。

后端开发 0 次安装 0 次浏览 更新于 2/28/2026

name: nodemailer description: 从Node.js应用发送邮件。最流行的邮件发送模块,支持SMTP、OAuth2、附件和HTML模板。 metadata: short-description: Node.js邮件发送 source: repository: https://github.com/nodemailer/nodemailer license: MIT stars: 17k+

Nodemailer 工具

描述

通过SMTP、OAuth2、附件和HTML模板从Node.js发送电子邮件。

源码

安装

npm install nodemailer

使用示例

基础邮件

import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
  host: 'smtp.gmail.com',
  port: 587,
  secure: false,
  auth: {
    user: process.env.EMAIL_USER,
    pass: process.env.EMAIL_PASS,
  },
});

async function sendEmail() {
  const info = await transporter.sendMail({
    from: '"我的应用" <noreply@myapp.com>',
    to: 'user@example.com',
    subject: '欢迎使用我的应用',
    text: '你好,欢迎使用我们的平台!',
    html: '<h1>你好</h1><p>欢迎使用我们的平台!</p>',
  });
  
  console.log('消息已发送:', info.messageId);
}

带模板的HTML邮件

async function sendWelcomeEmail(user: { name: string; email: string }) {
  const html = `
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          .container { max-width: 600px; margin: 0 auto; font-family: Arial; }
          .header { background: #4F46E5; color: white; padding: 20px; }
          .content { padding: 20px; }
          .button { background: #4F46E5; color: white; padding: 12px 24px; 
                    text-decoration: none; border-radius: 4px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>欢迎,${user.name}!</h1>
          </div>
          <div class="content">
            <p>感谢您加入我们的平台。</p>
            <a href="https://myapp.com/dashboard" class="button">开始使用</a>
          </div>
        </div>
      </body>
    </html>
  `;
  
  await transporter.sendMail({
    from: '"我的应用" <noreply@myapp.com>',
    to: user.email,
    subject: `欢迎,${user.name}!`,
    html,
  });
}

带附件的邮件

async function sendEmailWithAttachment() {
  await transporter.sendMail({
    from: '"报告" <reports@myapp.com>',
    to: 'manager@company.com',
    subject: '月度报告',
    text: '请查收月度报告附件。',
    attachments: [
      {
        filename: 'report.pdf',
        path: './reports/monthly-report.pdf',
      },
      {
        filename: 'data.xlsx',
        content: Buffer.from('...'), // 缓冲区内容
      },
      {
        filename: 'logo.png',
        path: './assets/logo.png',
        cid: 'logo@myapp', // 用于嵌入HTML
      },
    ],
    html: '<img src="cid:logo@myapp" /><p>请查看附件报告。</p>',
  });
}

OAuth2 认证 (Gmail)

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    type: 'OAuth2',
    user: process.env.GMAIL_USER,
    clientId: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    refreshToken: process.env.GOOGLE_REFRESH_TOKEN,
  },
});

带速率限制的邮件队列

class EmailQueue {
  private queue: Array<() => Promise<void>> = [];
  private processing = false;
  
  async add(emailFn: () => Promise<void>) {
    this.queue.push(emailFn);
    this.process();
  }
  
  private async process() {
    if (this.processing) return;
    this.processing = true;
    
    while (this.queue.length > 0) {
      const emailFn = this.queue.shift()!;
      await emailFn();
      await new Promise(r => setTimeout(r, 1000)); // 速率限制
    }
    
    this.processing = false;
  }
}

标签

邮件, smtp, 通知, 通信, 自动化

兼容性

  • Codex: ✅
  • Claude Code: ✅