TypeScript 发送邮件:nodemailer 库
Nodemailer 是 Node.js 和 TypeScript 中最流行的电子邮件发送模块。它支持通过 SMTP 以及内置传输服务(如 SendGrid、Mailgun 等)发送邮件。该库完全支持 TypeScript(包括类型定义),并支持纯文本邮件、HTML 邮件、附件以及加密功能。
为什么需要 nodemailer?
- 发送事务性邮件(注册确认、密码重置)。
- 发送通知邮件(例如网站订单后)。
- 与反馈表单集成。
- 自动化报告(每日数据转储)。
安装
npm install nodemailernpm install @types/nodemailer --save-dev主要功能
- SMTP 传输 — 可通过任何 SMTP 服务器进行配置(Gmail、Yandex、Mail.ru)。
- 支持 HTML 和纯文本 — 可发送纯文本或精美的 HTML 模板。
- 附件 — 支持文件、图片、PDF。
- 流式传输 — 无需加载到内存即可发送大文件。
- 类型定义 — 完全支持 TypeScript(提供选项的接口)。
TypeScript 代码示例
import nodemailer from 'nodemailer';
interface MailOptions { from: string; to: string; subject: string; text?: string; html?: string;}
async function sendEmail(options: MailOptions): Promise<void> { const transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 587, secure: false, auth: { user: 'your-email@gmail.com', pass: 'your-app-password' } });
const info = await transporter.sendMail(options); console.log('Email sent:', info.messageId);}
// 使用sendEmail({ from: 'noreply@example.com', to: 'user@example.com', subject: 'Hello from TypeScript', html: '<h1>Welcome!</h1><p>This is a test email.</p>'});何时使用 nodemailer?
该库非常适合基于 Node.js/TypeScript 的服务器端应用,尤其是与 Express、Next.js 或 Nest.js 配合使用时。如果您需要快速配置邮件发送而无需复杂配置,nodemailer 是最佳选择。它也适用于微服务和后台任务(例如,结合 Bull 或 Agenda 使用)。
重要说明
- 对于 Gmail,请使用应用密码(而非主密码)。
- 生产环境中请使用环境变量(例如
process.env.SMTP_PASS)。 - 别忘了处理错误:必须使用
try/catch。
Nodemailer 是 TypeScript 中发送电子邮件的实际标准。轻量、可靠且文档完善。