Envoi d'email en TypeScript : aperçu des bibliothèques et outils
L'envoi de courriels est l'une des tâches clés des applications web. En TypeScript (et son runtime Node.js), il existe plusieurs solutions matures. Dans cet article, nous examinerons les bibliothèques les plus populaires, leur configuration et des exemples d'utilisation avec une typage complet.
1. Nodemailer — client SMTP universel
Nodemailer est la bibliothèque la plus populaire pour l'envoi d'email en Node.js. Elle prend en charge SMTP, les transports intégrés (Sendmail, SES) et est entièrement compatible avec TypeScript grâce à ses types intégrés.
Installation
npm install nodemailernpm install --save-dev @types/nodemailerExemple d'envoi 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, });}
// UtilisationsendEmail({ to: 'user@example.com', subject: 'Bonjour depuis TypeScript !', text: 'Ceci est un email de test.',}).catch(console.error);Gestion des pièces jointes
await transporter.sendMail({ to: 'user@example.com', subject: 'Fichier en pièce jointe', text: 'Voir le document ci-joint.', attachments: [ { filename: 'report.pdf', path: './files/report.pdf', }, ],});2. SendGrid — service email cloud
SendGrid (maintenant partie de Twilio) fournit une API puissante pour l'envoi d'emails transactionnels et marketing. Pour TypeScript, il existe un package officiel avec des types prêts à l'emploi.
Installation
npm install @sendgrid/mailExemple d'envoi avec typage
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 envoyé via SendGrid'); } catch (error) { console.error('Erreur SendGrid :', error); }}
// UtilisationsendViaSendGrid({ to: 'client@example.com', from: 'noreply@myapp.com', subject: 'Confirmation d\'inscription', text: 'Bienvenue !', html: '<h1>Bienvenue !</h1><p>Merci de vous être inscrit</p>',});3. AWS SES — pour les systèmes à forte charge
AWS Simple Email Service (SES) est une solution d'entreprise pour l'envoi de gros volumes d'emails. Il s'utilise via le SDK @aws-sdk/client-ses.
Installation
npm install @aws-sdk/client-sesExemple avec 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, },