E-Mail-Versand mit TypeScript: Vollständiger Leitfaden mit nodemailer und SMTP

Online Python-Trainer für Anfänger

Lernen Sie Python einfach ohne theoretische Überlastung. Lösen Sie praktische Aufgaben mit automatischer Überprüfung und schreiben Sie Code direkt im Browser.

Kurs starten

E-Mail-Versand mit TypeScript: Vom Einfachen zum Komplexen



Das Versenden von E-Mails ist eine der Kernfunktionen jeder Webanwendung: Benutzerregistrierung, Passwort-Zurücksetzen, Bestellbenachrichtigungen, Newsletter. Im TypeScript- (und Node.js-) Ökosystem gibt es mehrere leistungsstarke Bibliotheken, die eine flexible Konfiguration des E-Mail-Versands ermöglichen. In diesem Artikel behandeln wir drei beliebte Tools: nodemailer, @sendgrid/mail und mailgun.js, zeigen TypeScript-Codebeispiele, besprechen die sichere Arbeit mit SMTP und die Templating-Erstellung.



1. nodemailer – Universeller SMTP-Client



nodemailer ist die beliebteste Bibliothek zum Versenden von E-Mails aus Node.js. Sie unterstützt alle SMTP-Server (Gmail, Yandex, Mail.ru, eigener Mail-Server) sowie integrierte Transporter für gängige Dienste. Dank der vorhandenen Typen funktioniert sie sofort mit TypeScript.



Installation

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


Basisbeispiel für den Versand über 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('E-Mail gesendet:', info.messageId);}

// VerwendungsendEmail({ to: 'user@example.com', subject: 'Hallo aus TypeScript!', text: 'Dies ist eine Test-E-Mail.', html: '<h1>Hallo!</h1><p>Dies ist die <strong>HTML</strong>-Version.</p>',}).catch(console.error);


Arbeiten mit mehreren Empfängern und Anhängen

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: '"Team" <no-reply@mydomain.ru>', to: ['user1@example.com', 'user2@example.com'], subject: 'Monatsbericht', text: 'Im Anhang finden Sie die Datei mit dem Bericht.', attachments: [ { filename: 'report.pdf', path: './docs/report.pdf', }, ], });}


2. SendGrid – Cloud-Dienst für große Volumen



SendGrid (Teil von Twilio) ist eine professionelle Plattform für E-Mail-Kampagnen. Sie bietet eine API, ein SDK für Node.js/TypeScript, Zustellungsanalysen und Spamschutz. Empfohlen für Projekte mit hoher Auslastung (tausende E-Mails pro Tag).



Installation und Konfiguration

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('E-Mail über SendGrid gesendet'); } catch (error) { console.error('SendGrid-Fehler:', error); throw error; }}


3. Mailgun – Alternative für Entwickler



Mailgun ist ein weiterer beliebter Dienst mit REST-API und TypeScript-Kompatibilität

Empfehlungen