使用 TypeScript 发送电子邮件:库和代码示例

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

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

开始课程

使用 TypeScript 发送电子邮件:库和工具概述



发送电子邮件是 Web 应用程序的关键任务之一。在 TypeScript(及其运行时 Node.js)中,有几种成熟的解决方案。在本文中,我们将介绍最流行的库、它们的配置以及带有完整类型注解的使用示例。



1. Nodemailer — 通用 SMTP 客户端



Nodemailer 是 Node.js 中最流行的电子邮件发送库。它支持 SMTP、内置传输(Sendmail、SES),并且由于内置类型,与 TypeScript 完全兼容。



安装

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


通过 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, }, });

await transporter.sendMail({ from: `"MyApp" <${process.env.EMAIL_USER}>`, to: options.to, subject: options.subject, text: options.text, html: options.html || options.text, });}

// 使用sendEmail({ to: 'user@example.com', subject: '来自 TypeScript 的问候!', text: '这是一封测试邮件。',}).catch(console.error);


处理附件

await transporter.sendMail({  to: 'user@example.com',  subject: '附件文件',  text: '请查看附件文档。',  attachments: [    {      filename: 'report.pdf',      path: './files/report.pdf',    },  ],});


2. SendGrid — 云电子邮件服务



SendGrid(现为 Twilio 的一部分)提供强大的 API,用于发送事务性和营销邮件。TypeScript 有官方包,带有现成的类型。



安装

npm install @sendgrid/mail


带类型注解的发送示例

import sgMail from '@sendgrid/mail';

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

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

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

// 使用sendViaSendGrid({ to: 'client@example.com', from: 'noreply@myapp.com', subject: '注册确认', text: '欢迎!', html: '<h1>欢迎!</h1><p>感谢您的注册</p>',});


3. AWS SES — 用于高负载系统



AWS Simple Email Service (SES) 是用于发送大量邮件的企业级解决方案。通过 SDK @aws-sdk/client-ses 使用。



安装

npm install @aws-sdk/client-ses


TypeScript 示例

import { SESClient, SendEmailCommand } from '@aws-sdk/client-ses';

const sesClient = new SESClient({ region: 'us-east-1', credentials: { accessKeyId: process.env.AWS_ACCESS_KEY!, secretAccessKey: process.env.AWS_SECRET_KEY!, },});

interface SESEmailParams { to: string[]; from: string; subject: string; bodyText: string; bodyHtml?: string;}

async function sendViaSES(params: SESEmailParams): Promise<void> { const command = new SendEmailCommand({ Destination: { ToAddresses: params.to, },

推荐