Envio de email em TypeScript: visão geral de bibliotecas e ferramentas
O envio de emails é uma das tarefas essenciais de aplicações web. Em TypeScript (e seu runtime Node.js), existem várias soluções maduras. Neste artigo, abordaremos as bibliotecas mais populares, sua configuração e exemplos de uso com tipagem completa.
1. Nodemailer — cliente SMTP universal
Nodemailer é a biblioteca mais popular para envio de email em Node.js. Ela suporta SMTP, transportes integrados (Sendmail, SES) e é totalmente compatível com TypeScript graças aos tipos nativos.
Instalação
npm install nodemailernpm install --save-dev @types/nodemailerExemplo de envio via 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, });}
// UsosendEmail({ to: 'user@example.com', subject: 'Olá do TypeScript!', text: 'Este é um email de teste.',}).catch(console.error);Trabalhando com anexos
await transporter.sendMail({ to: 'user@example.com', subject: 'Arquivo anexado', text: 'Veja o documento anexado.', attachments: [ { filename: 'report.pdf', path: './files/report.pdf', }, ],});2. SendGrid — serviço de email em nuvem
SendGrid (agora parte da Twilio) fornece uma API poderosa para envio de emails transacionais e de marketing. Para TypeScript, existe um pacote oficial com tipos prontos.
Instalação
npm install @sendgrid/mailExemplo de envio com tipagem
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('Email enviado via SendGrid'); } catch (error) { console.error('Erro no SendGrid:', error); }}
// UsosendViaSendGrid({ to: 'client@example.com', from: 'noreply@myapp.com', subject: 'Confirmação de registro', text: 'Bem-vindo!', html: '<h1>Bem-vindo!</h1><p>Obrigado por se registrar</p>',});3. AWS SES — para sistemas de alta carga
AWS Simple Email Service (SES) é uma solução corporativa para envio de grandes volumes de emails. É usado através do SDK @aws-sdk/client-ses.
Instalação
npm install @aws-sdk/client-sesExemplo com 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, },