TypeScript 邮件发送:使用 nodemailer 和 SMTP 的完整指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

TypeScript 邮件发送:从入门到精通



发送电子邮件是任何 Web 应用程序的关键功能之一:用户注册、密码重置、订单通知、新闻通讯。在 TypeScript(和 Node.js)生态系统中,有多个强大的库可以灵活配置邮件发送。在本文中,我们将介绍三种流行的工具:nodemailer、@sendgrid/mail 和 mailgun.js,展示 TypeScript 代码示例,讨论 SMTP 的安全使用以及模板化。



1. nodemailer — 通用 SMTP 客户端



nodemailer 是从 Node.js 发送邮件最流行的库。它支持任何 SMTP 服务器(Gmail、Yandex、Mail.ru、自有邮件服务器),以及内置的流行服务传输器。由于提供了类型定义,它可以与 TypeScript 开箱即用。



安装

npm install nodemailernpm install @types/nodemailer --save-dev


通过 Gmail SMTP 发送的基本示例

import nodemailer from 'nodemailer';

interface EmailOptions { to: string; subject: string; text: string; html?: string;}

async function sendEmail(options: EmailOptions): Promise<void> { const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: process.env.EMAIL_USER, pass: process.env.EMAIL_PASS, }, });

const mailOptions = { from: `"My App" <${process.env.EMAIL_USER}>`, to: options.to, subject: options.subject, text: options.text, html: options.html, };

const info = await transporter.sendMail(mailOptions); console.log('邮件已发送:', info.messageId);}

// 使用sendEmail({ to: 'user@example.com', subject: '来自 TypeScript 的问候!', text: '这是一封测试邮件。', html: '<h1>你好!</h1><p>这是 <strong>HTML</strong> 版本。</p>',}).catch(console.error);


处理多个收件人和附件

async function sendBulkWithAttachments(): Promise<void> {  const transporter = nodemailer.createTransport({    host: 'smtp.yandex.ru',    port: 465,    secure: true,    auth: {      user: process.env.YANDEX_USER,      pass: process.env.YANDEX_PASS,    },  });

await transporter.sendMail({ from: '"团队" <no-reply@mydomain.ru>', to: ['user1@example.com', 'user2@example.com'], subject: '月度报告', text: '附件中包含报告文件。', attachments: [ { filename: 'report.pdf', path: './docs/report.pdf', }, ], });}


2. SendGrid — 适用于大容量的云服务



SendGrid(Twilio 的一部分)是一个专业的邮件发送平台。它提供 API、Node.js/TypeScript SDK、投递分析以及反垃圾邮件保护。推荐用于高负载项目(每天数千封邮件)。



安装与配置

npm install @sendgrid/mail


import sgMail from '@sendgrid/mail';

sgMail.setApiKey(process.env.SENDGRID_API_KEY!);

interface SendGridOptions { to: string | string[]; subject: string; html: string; from?: string;}

async function sendViaSendGrid(options: SendGridOptions): Promise<void> { const msg = { to: options.to, from: options.from || 'noreply@mydomain.com', subject: options.subject, html: options.html, };

try { await sgMail.send(msg); console.log('通过 SendGrid 发送邮件'); } catch (error) { console.error('SendGrid 错误:', error); throw error; }}


3. Mailgun — 面向开发者的替代方案



Mailgun 是另一个流行的服务,提供 REST API 和 TypeScript 兼容性

推荐