在 TypeScript 中发送电子邮件:库与代码示例

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

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

开始课程

TypeScript 电子邮件发送:完整指南

TypeScript 是 JavaScript 的强类型超集,在现代 Web 应用中广泛使用。发送电子邮件是后端、通知和营销的关键任务之一。本文将详细介绍几个用于在 TypeScript 中发送电子邮件的库,包括配置、发送纯文本和 HTML 邮件,以及处理附件。



为什么选择 TypeScript 发送电子邮件?

TypeScript 增加了类型检查,从而减少了开发阶段的错误。在发送电子邮件时,这一点尤为重要:为 SMTP 主机、端口、凭证和邮件选项设置正确的类型有助于避免运行时错误。此外,TypeScript 支持现代的 async/await 语法,使代码更清晰、更易理解。



用于 TypeScript 发送电子邮件的主要库

  • nodemailer — 最流行的 Node.js 库,完全兼容 TypeScript。支持 SMTP、Sendmail、附件、HTML 模板。
  • @sendgrid/mail — SendGrid 官方 Node.js 客户端,带有 TypeScript 类型。使用 SendGrid API,无需 SMTP。
  • aws-sdk (SES) — Amazon Simple Email Service。用于批量发送的强大解决方案,与 AWS 集成。
  • emailjs — 轻量级库,支持 TypeScript,但不太流行。


使用 TypeScript 安装和配置 nodemailer

通过 npm 安装包:

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

通过 SMTP(Gmail、Yandex、Mail.ru 等)发送电子邮件的基本示例:

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({ host: 'smtp.gmail.com', port: 587, secure: false, // true 用于 465 端口 auth: { user: 'your-email@gmail.com', pass: 'your-password-or-app-password', }, });

const mailOptions = { from: '"您的姓名" <your-email@gmail.com>', 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 的问候!', html: '<h1>测试</h1><p>这是一封 HTML 邮件。</p>',});

重要提示: 对于 Gmail,请启用“允许不够安全的应用”或使用应用密码(App Password)。生产环境建议使用 OAuth2。



通过 SendGrid 在 TypeScript 中发送电子邮件

SendGrid 提供现成的 API,无需 SMTP。安装:

npm install @sendgrid/mail

发送示例:

import sgMail from '@sendgrid/mail';

sgMail.setApiKey('YOUR_SENDGRID_API_KEY');

interface SendGridMessage { to: string; from: string; subject: string; html: string;}

async function sendWithSendGrid(message: SendGridMessage): Promise<void> { try { await sgMail.send(message); console.log('通过 SendGrid 发送的电子邮件'); } catch (error) { console.error('发送错误:', error); }}

sendWithSendGrid({ to: 'user@example.com', from: 'sender@yourdomain.com', subject: 'SendGrid + TypeScript 测试', html: '<p>此消息通过 SendGrid API 发送。</p>',});


在 TypeScript 中发送带附件的电子邮件

nodemailer 支持任何类型的附件。带有 PDF 文件的示例:

import nodemailer from 'nodemailer';import path from 'path';

async function sendWithAttachment()

推荐