### Proxy Configuration Example Source: https://nodemailer.com/errors Example of setting up a Nodemailer transporter with proxy configuration. ```javascript const transporter = nodemailer.createTransport({ host: "smtp.example.com", port: 587, proxy: "http://proxy.example.com:3128", }); ``` -------------------------------- ### Complete DSN Workflow with Nodemailer and smtp-server Source: https://nodemailer.com/extras/smtp-server This example demonstrates a full DSN implementation, including setting up a Nodemailer transporter for notifications, a DSNNotifier class, and an SMTP server that handles DSN parameters and sends success notifications upon message delivery. It requires Nodemailer and smtp-server to be installed. ```javascript const { SMTPServer } = require("smtp-server"); const nodemailer = require("nodemailer"); // Create a Nodemailer transporter for sending DSN notifications const dsnTransporter = nodemailer.createTransport({ host: "smtp.example.com", port: 587, secure: false, auth: { user: "dsn-sender@example.com", pass: "your-password", }, }); // DSN notification generator class DSNNotifier { constructor(transporter) { this.transporter = transporter; } async sendSuccessNotification(envelope, messageId, deliveryTime) { // Only send if SUCCESS notification was requested const needsSuccessNotification = envelope.rcptTo.some((rcpt) => rcpt.dsn.notify && rcpt.dsn.notify.includes("SUCCESS")); if (!needsSuccessNotification || !envelope.mailFrom.address) { return; } const dsnMessage = this.generateDSNMessage({ action: "delivered", status: "2.0.0", envelope, messageId, deliveryTime, diagnosticCode: "smtp; 250 2.0.0 Message accepted for delivery", }); await this.transporter.sendMail({ from: "postmaster@example.com", to: envelope.mailFrom.address, subject: "Delivery Status Notification (Success)", text: dsnMessage.text, headers: { "Auto-Submitted": "auto-replied", "Content-Type": "multipart/report; report-type=delivery-status", }, }); } generateDSNMessage({ action, status, envelope, messageId, deliveryTime, diagnosticCode }) { const { dsn } = envelope; const timestamp = deliveryTime || new Date().toISOString(); // Generate RFC 3464 compliant delivery status notification const text = `This is an automatically generated Delivery Status Notification. Original Message Details: - Message ID: ${messageId} - Envelope ID: ${dsn.envid || "Not provided"} - Sender: ${envelope.mailFrom.address} - Recipients: ${envelope.rcptTo.map((r) => r.address).join(", ")} - Action: ${action} - Status: ${status} - Time: ${timestamp} ${action === "delivered" ? "Your message has been successfully delivered to all recipients." : "Delivery failed for one or more recipients."} `; return { text }; } } // Create DSN notifier instance const dsnNotifier = new DSNNotifier(dsnTransporter); // SMTP Server with DSN support const server = new SMTPServer({ hideDSN: false, // Required to enable DSN name: "mail.example.com", onMailFrom(address, session, callback) { const { dsn } = session.envelope; console.log(`MAIL FROM: ${address.address}, RET=${dsn.ret}, ENVID=${dsn.envid}`); callback(); }, onRcptTo(address, session, callback) { const { notify, orcpt } = address.dsn; console.log(`RCPT TO: ${address.address}, NOTIFY=${notify?.join(",")}, ORCPT=${orcpt}`); callback(); }, async onData(stream, session, callback) { const messageId = `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; stream.on("end", async () => { try { // Simulate message delivery const deliveryTime = new Date(); // Send DSN success notification if requested await dsnNotifier.sendSuccessNotification(session.envelope, messageId, deliveryTime); callback(null, `Message ${messageId} accepted for delivery`); } catch (error) { callback(error); } }); stream.resume(); }, }); server.listen(2525, () => { console.log("DSN-enabled SMTP server listening on port 2525"); }); ``` -------------------------------- ### Install smtp-server Source: https://nodemailer.com/extras/smtp-server Install the smtp-server module using npm. This is the first step before requiring it in your script. ```bash npm install smtp-server --save ``` -------------------------------- ### Install MailParser Source: https://nodemailer.com/extras/mailparser Install the mailparser package using npm. ```bash npm install mailparser ``` -------------------------------- ### Complete Ethereal Email Testing Example Source: https://nodemailer.com/guides/testing-with-ethereal A full example demonstrating how to create a test account, set up a transporter, send an email, and log the message ID and preview URL. This is suitable for a complete test run. ```javascript const nodemailer = require("nodemailer"); async function sendTestEmail() { // Generate a test account const testAccount = await nodemailer.createTestAccount(); console.log("Test account created:"); console.log(" User: %s", testAccount.user); console.log(" Pass: %s", testAccount.pass); // Create a transporter const transporter = nodemailer.createTransport({ host: testAccount.smtp.host, port: testAccount.smtp.port, secure: testAccount.smtp.secure, auth: { user: testAccount.user, pass: testAccount.pass, }, }); // Send a test message const info = await transporter.sendMail({ from: `"Test App" <${testAccount.user}>`, to: "recipient@example.com", subject: "Hello from Ethereal!", text: "This message was sent using Ethereal.", html: "

This message was sent using Ethereal.

", }); console.log("Message sent: %s", info.messageId); console.log("Preview: %s", nodemailer.getTestMessageUrl(info)); } sendTestEmail().catch(console.error); ``` -------------------------------- ### Complete DSN Example with SMTPServer Source: https://nodemailer.com/extras/smtp-server A comprehensive example showing how to enable DSN support and access DSN parameters in `onMailFrom`, `onRcptTo`, and `onData` handlers for processing messages with DSN context. ```javascript const server = new SMTPServer({ hideDSN: false, // Required to enable DSN onMailFrom(address, session, callback) { const { ret, envid } = session.envelope.dsn; console.log(`Mail from ${address.address}, RET=${ret}, ENVID=${envid}`); callback(); }, onRcptTo(address, session, callback) { const { notify, orcpt } = address.dsn; console.log(`Rcpt to ${address.address}, NOTIFY=${notify.join(",")}, ORCPT=${orcpt}`); callback(); }, onData(stream, session, callback) { // Process message with DSN context const { dsn } = session.envelope; console.log(`Processing message with DSN: ${JSON.stringify(dsn)}`); stream.on("end", () => { callback(null, "Message accepted for delivery"); }); stream.resume(); }, }); ``` -------------------------------- ### Install AWS SES SDK v3 Source: https://nodemailer.com/transports/ses Install the necessary AWS SDK v3 package for SES. ```bash npm install @aws-sdk/client-sesv2 ``` -------------------------------- ### Complete Email Sending Example with Mixed Addresses Source: https://nodemailer.com/message/addresses A full example demonstrating how to create a Nodemailer transport and send an email using a mix of address formats for the 'from' and 'to' fields. ```javascript const nodemailer = require("nodemailer"); async function sendEmail() { // Create a transport with your SMTP server settings const transport = nodemailer.createTransport({ host: "smtp.example.com", port: 587, auth: { user: "smtp-user", pass: "smtp-pass" } }); // Send an email using mixed address formats await transport.sendMail({ from: '"Example Sender" ', to: [ "recipient@example.com", // Plain address { name: "Nodemailer User", address: "user@example.com" } // Address object ], subject: "Hello from Nodemailer", text: "This demonstrates the different address formats." }); } sendEmail().catch(console.error); ``` -------------------------------- ### Install Nodemailer Source: https://nodemailer.com/ Install Nodemailer using npm. This is the first step to using the library in your Node.js project. ```bash npm install nodemailer ``` -------------------------------- ### Start SMTP server listening Source: https://nodemailer.com/extras/smtp-server Begin listening for incoming connections on a specified port and optional host. ```javascript server.listen(port[, host][, callback]); ``` -------------------------------- ### Install SOCKS Package Source: https://nodemailer.com/smtp/proxies Install the 'socks' package using npm to enable SOCKS proxy support in Nodemailer. This is a necessary step before configuring the transporter for SOCKS proxies. ```bash npm install socks --save ``` -------------------------------- ### Greeting with Both Placeholders Source: https://nodemailer.com/extras/smtp-server Example of using both server name and client hostname placeholders in the HELO/EHLO greeting. ```javascript heloResponse: "%s greets %s" ``` -------------------------------- ### Simple Greeting Example Source: https://nodemailer.com/extras/smtp-server Example of a simple greeting without placeholders for the HELO/EHLO response. ```javascript heloResponse: "Hello" ``` -------------------------------- ### Password-Based Authentication (PLAIN/LOGIN) Source: https://nodemailer.com/extras/smtp-server Example of handling password-based authentication by checking username and password. ```javascript onAuth(auth, session, callback) { if (auth.username !== "alice" || auth.password !== "s3cr3t") { return callback(new Error("Invalid username or password")); } callback(null, { user: auth.username }); } ``` -------------------------------- ### Install Dependencies for SES Transport Source: https://nodemailer.com/transports Install Nodemailer and the AWS SDK v3 client for SES v2. ```bash npm install nodemailer @aws-sdk/client-sesv2 ``` -------------------------------- ### OAuth 2 Authentication (XOAUTH2) Source: https://nodemailer.com/extras/smtp-server Example for handling OAuth 2.0 authentication using the `XOAUTH2` method. Requires a valid access token. ```javascript const server = new SMTPServer({ authMethods: ["XOAUTH2"], onAuth(auth, session, callback) { if (auth.accessToken !== "ya29.a0Af...") { // Return OAuth error response per RFC 6750 Section 3 return callback(null, { data: { status: "401", schemes: "bearer" }, }); } callback(null, { user: auth.username }); }, }); ``` -------------------------------- ### Example Custom Authentication Handler Source: https://nodemailer.com/smtp/customauth This example demonstrates how to define and use a custom authentication handler for an SMTP server. It sends a base64-encoded password as part of the AUTH command. Ensure the server's requirements for the custom method are met. ```javascript const nodemailer = require("nodemailer"); // Define the custom authentication handler async function myCustomMethod(ctx) { // Build and send the AUTH command with your custom data // This example sends a base64-encoded password (adapt to your server's requirements) const response = await ctx.sendCommand( "AUTH MY-CUSTOM-METHOD " + Buffer.from(ctx.auth.credentials.pass).toString("base64") ); // Check if the server accepted the authentication // SMTP success codes are in the 2xx range (typically 235 for successful auth) if (response.status < 200 || response.status >= 300) { throw new Error("Authentication failed: " + response.text); } } const transporter = nodemailer.createTransport({ host: "smtp.example.com", port: 465, secure: true, auth: { type: "custom", // tells Nodemailer to use a custom handler method: "MY-CUSTOM-METHOD", // specifies which handler to use user: "username", pass: "verysecret", }, customAuth: { "MY-CUSTOM-METHOD": myCustomMethod, }, }); ``` -------------------------------- ### Custom Logger Setup for Nodemailer Source: https://nodemailer.com/smtp Demonstrates how to create a Nodemailer-compatible logger wrapper for libraries like Pino. This allows for custom logging of SMTP events and protocol traffic. ```javascript const smtpLogger = {}; // Set up logger wrapper for each log level for (let level of ['trace', 'debug', 'info', 'warn', 'error', 'fatal']) { smtpLogger[level] = (data, message, ...args) => { if (args && args.length) { message = util.format(message, ...args); } data.msg = message; data.src = 'nodemailer'; if (typeof pinoLogger[level] === 'function') { pinoLogger[level](data); } else { pinoLogger.debug(data); } }; } nodemailer.createTransport({ // ... other options logger: smtpLogger }) ``` -------------------------------- ### Client MAIL FROM with DSN Parameters Source: https://nodemailer.com/extras/smtp-server Example of a client sending a MAIL FROM command with DSN parameters `RET` and `ENVID` to request specific delivery status notifications. ```text // Client sends: MAIL FROM: RET=FULL ENVID=abc123 ``` -------------------------------- ### Client RCPT TO with DSN Parameters Source: https://nodemailer.com/extras/smtp-server Example of a client sending a RCPT TO command with DSN parameters `NOTIFY` and `ORCPT` to specify notification conditions and the original recipient. ```text // Client sends: RCPT TO: NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;user@example.com ``` -------------------------------- ### AMP4EMAIL Example Source: https://nodemailer.com/message Include AMP content alongside standard text and HTML versions for interactive emails. Clients supporting AMP will render it; others will fall back to HTML or plaintext. ```javascript const message = { from: "Nodemailer ", to: "Nodemailer ", subject: "AMP4EMAIL message", text: "For clients with plaintext support only", html: "

For clients that do not support AMP4EMAIL or when AMP content is invalid

", amp: `

Image:

GIF (requires "amp-anim" script in header):

`, }; ``` -------------------------------- ### build(callback) Source: https://nodemailer.com/extras/mailcomposer Generates the complete message and returns it as a Buffer through a callback function. Use this method when you need the entire message in memory, for example to save it to a file or send it via an API. ```APIDOC ## build(callback) ### Description Generates the complete message and returns it as a `Buffer` through a callback function. Use this method when you need the entire message in memory, for example to save it to a file or send it via an API. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters * **callback** (function) - Required - A callback function that receives an error (if any) and the message Buffer. ### Request Example ```javascript const mail = new MailComposer({ from: "you@example.com" /* ... */ }); mail.compile().build((err, message) => { if (err) throw err; process.stdout.write(message); }); ``` ### Response #### Success Response The complete message as a Buffer. #### Response Example (Buffer output to process.stdout) ``` -------------------------------- ### Send Email with List Headers Source: https://nodemailer.com/message/list-headers This example demonstrates how to send an email with various List-* headers using Nodemailer's 'list' option. It shows different formats for defining help, unsubscribe, subscribe, and post headers. ```javascript const nodemailer = require("nodemailer"); // 1. Create a transport (replace with your configuration) const transporter = nodemailer.createTransport({ host: "smtp.example.com", port: 587, auth: { user: "username", pass: "password", }, }); // 2. Send a message with various List-* headers async function sendListMessage() { await transporter.sendMail({ from: "sender@example.com", to: "recipient@example.com", subject: "List Message", text: "I hope no one unsubscribes from this list!", list: { // List-Help: help: "admin@example.com?subject=help", // List-Unsubscribe: (Comment) unsubscribe: { url: "http://example.com", comment: "Comment", }, // Two separate List-Subscribe header lines: // List-Subscribe: // List-Subscribe: (Subscribe) subscribe: [ "admin@example.com?subject=subscribe", { url: "http://example.com", comment: "Subscribe", }, ], // Multiple URLs in a single List-Post header line: // List-Post: , (Post) post: [ [ "http://example.com/post", { url: "admin@example.com?subject=post", comment: "Post", }, ], ], }, }); console.log("List message sent"); } sendListMessage().catch(console.error); ``` -------------------------------- ### Nodemailer Email Attachments Examples Source: https://nodemailer.com/message/attachments Demonstrates various ways to attach files to an email using Nodemailer. Includes plain text, buffers, file paths, streams, URLs, and base64 encoding. Prefer 'path' or 'href' for large files to enable streaming. ```javascript const fs = require("fs"); // The attachments array goes inside your message object attachments: [ // 1. Plain text string // The simplest way to create an attachment from a string { filename: "hello.txt", content: "Hello world!", }, // 2. Buffer content // Useful when you have binary data in memory { filename: "buffer.txt", content: Buffer.from("Hello world!", "utf8"), }, // 3. File from the filesystem // Uses streaming, which is memory-efficient for large files { filename: "report.pdf", path: "/absolute/path/to/report.pdf", }, // 4. File path only // When you omit filename, Nodemailer derives it from the path // The content type is also automatically detected from the file extension { path: "/absolute/path/to/image.png", }, // 5. Readable stream // Provides full control over how content is read { filename: "notes.txt", content: fs.createReadStream("./notes.txt"), }, // 6. Explicit content type // Override automatic MIME type detection when needed { filename: "data.bin", content: Buffer.from("deadbeef", "hex"), contentType: "application/octet-stream", }, // 7. Remote URL // Nodemailer fetches the content from the URL when sending { filename: "license.txt", href: "https://raw.githubusercontent.com/nodemailer/nodemailer/master/LICENSE", }, // 8. Base64-encoded string // Specify the encoding when your content string is not plain text { filename: "photo.jpg", content: "/9j/4AAQSkZJRgABAQAAAQABAAD...", // base64 image data (truncated) encoding: "base64", }, // 9. Data URI // Useful for inline data or content from canvas elements { path: "data:text/plain;base64,SGVsbG8gd29ybGQ=", }, // 10. Pre-built MIME node (advanced) // Provides complete control over the attachment's MIME structure { raw: [ "Content-Type: text/plain; charset=utf-8", 'Content-Disposition: attachment; filename="greeting.txt"', "", "Hello world!" ].join("\r\n"), }, ]; ``` -------------------------------- ### Example: Generate Plain Text from HTML Source: https://nodemailer.com/plugins/create A 'compile' plugin that generates plain text content from HTML if plain text is not provided. It modifies `mail.data.text` by stripping HTML tags. ```javascript transporter.use("compile", (mail, done) => { if (!mail.data.text && mail.data.html) { mail.data.text = mail.data.html.replace(/<[^>]*>/g, " "); } done(); }); ``` -------------------------------- ### Example: Log All Address Fields Source: https://nodemailer.com/plugins/create A 'stream' plugin that logs the 'from', 'to', 'cc', and 'bcc' address fields of the message. It retrieves these fields from the `mail.message` object. ```javascript transporter.use("stream", (mail, done) => { const a = mail.message.getAddresses(); console.log("From :", JSON.stringify(a.from)); console.log("To :", JSON.stringify(a.to)); console.log("Cc :", JSON.stringify(a.cc)); console.log("Bcc :", JSON.stringify(a.bcc)); done(); }); ``` -------------------------------- ### Create Transporter with Connection URL Source: https://nodemailer.com/smtp Configure a transporter using a connection URL. Supports 'smtps:' for TLS from the start and 'direct:' for direct MX server delivery. Connection pooling can be enabled via query parameters. ```javascript // Pooled connection via TLS const transporter = nodemailer.createTransport( "smtps://username:password@smtp.example.com/?pool=true" ); // Direct delivery to the recipient's MX server (no relay) const transporter = nodemailer.createTransport("direct:?name=hostname.example.com"); ``` -------------------------------- ### Example: Log Final HTML String Source: https://nodemailer.com/plugins/create This plugin function resolves the 'html' content from `mail.data` and logs it to the console. It ensures the content is processed before continuing. ```javascript function plugin(mail, done) { mail.resolveContent(mail.data, "html", (err, html) => { if (err) return done(err); console.log("HTML contents: %s", html.toString()); done(); }); } ``` -------------------------------- ### Quick Start: Send Email with SES Transport Source: https://nodemailer.com/transports/ses Configure Nodemailer to use the SES transport and send a basic email. Ensure AWS credentials are set up for the SDK. ```javascript const nodemailer = require("nodemailer"); const { SESv2Client, SendEmailCommand } = require("@aws-sdk/client-sesv2"); // 1. Create an AWS SES client // If you omit credentials, the SDK uses the default credential chain // (environment variables, shared credentials file, IAM role, etc.) const sesClient = new SESv2Client({ region: "us-east-1" }); // 2. Create a Nodemailer transport configured to use SES const transporter = nodemailer.createTransport({ SES: { sesClient, SendEmailCommand }, }); // 3. Send the message const info = await transporter.sendMail({ from: "sender@example.com", to: "recipient@example.com", subject: "Hello from Nodemailer + SES", text: "I hope this message gets sent!", // You can pass additional SES-specific options under the `ses` key: ses: { ConfigurationSetName: "my-config-set", EmailTags: [{ Name: "tag_name", Value: "tag_value" }], }, }); console.log(info.envelope); // { from: "sender@example.com", to: ["recipient@example.com"] } console.log(info.messageId); // The SES Message ID ``` -------------------------------- ### Create Custom Nodemailer Transport Source: https://nodemailer.com/plugins/create Implement a custom transport object with 'name', 'version', and 'send' methods. This example pipes the message to stdout for demonstration. ```javascript const nodemailer = require("nodemailer"); const transport = { name: require("./package.json").name, // e.g. "SMTP" version: require("./package.json").version, // e.g. "1.0.0" /** * Sends the message. * @param {Object} mail - The same `mail` object that plugins receive * @param {Function} done - Callback with signature `(err, info)` */ send(mail, done) { const input = mail.message.createReadStream(); const envelope = mail.message.getEnvelope(); const messageId = mail.message.messageId(); // For demonstration, we pipe the message to stdout input.pipe(process.stdout); input.on("end", () => { done(null, { envelope, messageId, }); }); }, /** * Optional: Clean up resources when the transporter is closed. * Useful for closing long-lived connections (e.g., pooled SMTP). */ close() { // Release resources here }, /** * Optional: Report whether the transport is idle. * Used by connection pooling. Return `true` when the transport * has capacity to send more messages immediately. */ isIdle() { return true; }, }; const transporter = nodemailer.createTransport(transport); transporter.sendMail( { from: "sender@example.com", to: "receiver@example.com", subject: "Hello", text: "Hello world!", }, console.log ); ``` -------------------------------- ### Example Compile Plugin for Plain Text Generation Source: https://nodemailer.com/plugins This plugin automatically generates a plain-text version of an email if only HTML is provided. It uses the 'html-to-text' package. Always call the callback when done, passing an Error object to abort sending. ```javascript // CommonJS module format module.exports = function myCompilePlugin(mail, callback) { // The mail object contains a `data` property with your message options // You can read and modify these properties before the message is compiled if (!mail.data.text && mail.data.html) { // Generate plain-text from HTML using the html-to-text package mail.data.text = require("html-to-text").htmlToText(mail.data.html); } // Always call the callback when done // Pass no arguments for success, or pass an Error to abort sending callback(); }; ``` -------------------------------- ### Specify Custom Sendmail Binary Path Source: https://nodemailer.com/transports/sendmail Use the `path` option to specify the exact location of the sendmail binary if it's not in the system's PATH. This example also demonstrates sending an email using the configured transport. ```javascript const nodemailer = require("nodemailer"); const transporter = nodemailer.createTransport({ sendmail: true, newline: "unix", path: "/usr/sbin/sendmail", }); transporter.sendMail( { from: "sender@example.com", to: "recipient@example.com", subject: "Test message", text: "I hope this message gets delivered!", }, (err, info) => { if (err) { console.error(err); return; } console.log(info.envelope); console.log(info.messageId); } ); ``` -------------------------------- ### Return Buffer with Unix Line Endings Source: https://nodemailer.com/transports/stream Configure the transporter to return the complete message as a Buffer in memory by setting `buffer: true`. This example also explicitly uses Unix-style LF line endings, which is the default. ```javascript const nodemailer = require("nodemailer"); const transporter = nodemailer.createTransport({ streamTransport: true, buffer: true, // Return a Buffer instead of a stream newline: "unix", // Use LF (\n) line endings (this is the default) }); transporter.sendMail( { from: "sender@example.com", to: "recipient@example.com", subject: "Buffered message", text: "This message is buffered using LF line endings.", }, (err, info) => { if (err) throw err; console.log(info.envelope); console.log(info.messageId); // The complete message is available as a Buffer console.log(info.message.toString()); } ); ``` -------------------------------- ### Create Nodemailer Transport with Single Connection Source: https://nodemailer.com/smtp Sets up a basic SMTP transporter using a single connection. The connection starts unencrypted and attempts to upgrade to TLS using STARTTLS if supported by the server. ```javascript const transporter = nodemailer.createTransport({ host: "smtp.example.com", port: 587, secure: false, // Start unencrypted, upgrade via STARTTLS auth: { user: "username", pass: "password", }, }); ``` -------------------------------- ### Resulting Email Headers Source: https://nodemailer.com/message/list-headers This snippet shows the exact email headers generated by the 'list' option in the previous example. It illustrates how Nodemailer formats the List-* headers based on the provided values. ```text List-Help: List-Unsubscribe: (Comment) List-Subscribe: List-Subscribe: (Subscribe) List-Post: , (Post) ``` -------------------------------- ### Configure TLS and STARTTLS Source: https://nodemailer.com/extras/smtp-server Enable TLS for secure connections or STARTTLS by providing certificate and key files. Uses a self-signed certificate for localhost if not configured. ```javascript const fs = require("fs"); const server = new SMTPServer({ secure: true, key: fs.readFileSync("private.key"), cert: fs.readFileSync("server.crt"), }); server.listen(465); ``` -------------------------------- ### Custom Formal Greeting Example Source: https://nodemailer.com/extras/smtp-server Example of a custom formal greeting for the HELO/EHLO response. ```javascript heloResponse: "Welcome to %s mail server" ``` -------------------------------- ### Create SMTPServer instance Source: https://nodemailer.com/extras/smtp-server Instantiate the SMTPServer with optional configuration settings. ```javascript const server = new SMTPServer(options); ``` -------------------------------- ### JSON Message Output Example Source: https://nodemailer.com/transports/stream An example of the JSON string output generated by Nodemailer when using `jsonTransport: true`. This format is useful for storing or passing message data. ```json { "from": { "address": "sender@example.com", "name": "" }, "to": [{ "address": "recipient@example.com", "name": "" }], "subject": "JSON message", "text": "I hope this message gets JSON-ified!", "headers": {}, "messageId": "<77a3458f-8070-339d-095f-85bb73f3db8e@example.com>" } ``` -------------------------------- ### Register a Plugin Source: https://nodemailer.com/plugins/create Use the `use()` method on your transporter to register a plugin for either the 'compile' or 'stream' stage. ```javascript transporter.use(step, pluginFn); ``` -------------------------------- ### Complete SMTP Connection Workflow Source: https://nodemailer.com/extras/smtp-connection Demonstrates the full process of connecting to an SMTP server, authenticating, sending an email, and closing the connection using SMTPConnection. ```javascript const SMTPConnection = require("nodemailer/lib/smtp-connection"); const connection = new SMTPConnection({ host: "smtp.example.com", port: 587, secure: false, debug: true, logger: true, }); connection.on("error", (err) => { console.error("Connection error:", err); }); connection.connect((err) => { if (err) { console.error("Failed to connect:", err); return; } connection.login( { user: "username", pass: "password", }, (err) => { if (err) { console.error("Authentication failed:", err); connection.close(); return; } const envelope = { from: "sender@example.com", to: ["recipient@example.com"], }; const message = `From: sender@example.com To: recipient@example.com Subject: Test Message Content-Type: text/plain; charset=utf-8 Hello from SMTPConnection!`; connection.send(envelope, message, (err, info) => { if (err) { console.error("Failed to send:", err); } else { console.log("Message sent!"); console.log("Accepted:", info.accepted); console.log("Rejected:", info.rejected); console.log("Response:", info.response); } connection.quit(); }); } ); }); ``` -------------------------------- ### Multiple Recipients Array Format Source: https://nodemailer.com/message/playground Provides an example of specifying multiple recipients using a JavaScript array. ```javascript "to": ["user1@example.com", "user2@example.com"] ``` -------------------------------- ### Formatting Email Addresses as Strings Source: https://nodemailer.com/extras/mailcomposer Illustrates the basic string format for specifying email addresses, including simple addresses and those with display names. ```plaintext recipient@example.com "Display Name" ``` -------------------------------- ### Example Nodemailer Error Object Source: https://nodemailer.com/errors Illustrates the structure of an error object generated by Nodemailer, including message, code, command, response, and responseCode. ```javascript { message: 'Invalid login: 535 5.7.8 Authentication failed', code: 'EAUTH', command: 'AUTH PLAIN', response: '535 5.7.8 Authentication failed', responseCode: 535 } ``` -------------------------------- ### Address Object Structure Source: https://nodemailer.com/extras/mailparser An example of the address object structure returned by MailParser for email addresses. It includes 'value', 'html', and 'text' representations. ```json { "value": [ { "name": "Jane Doe", "address": "jane@example.com" } ], "html": "Jane Doe <jane@example.com>", "text": "Jane Doe " } ``` -------------------------------- ### Create MailComposer Instance Source: https://nodemailer.com/extras/mailcomposer Instantiate MailComposer with mail options to define the email message. Refer to the 'Message fields' section for available options. ```javascript const mail = new MailComposer(mailOptions); ``` -------------------------------- ### Custom OAuth2 Token Handler Source: https://nodemailer.com/smtp/oauth2 Use this when you manage tokens separately and need to provide them on demand. Nodemailer will call this handler to get tokens. ```javascript let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 465, secure: true, auth: { type: "OAuth2", user: "user@example.com" }, }); transporter.set("oauth2_provision_cb", (user, renew, cb) => { cb(null, userTokens[user]); }); ``` -------------------------------- ### Send Email using SES Transport Source: https://nodemailer.com/transports/ses Example of sending an email using the SES transport with Nodemailer, including setting email tags for tracking. ```javascript const nodemailer = require("nodemailer"); const { SESv2Client, SendEmailCommand } = require("@aws-sdk/client-sesv2"); // Create the SES client using the AWS_REGION environment variable const sesClient = new SESv2Client({ region: process.env.AWS_REGION }); // Create the Nodemailer transport const transporter = nodemailer.createTransport({ SES: { sesClient, SendEmailCommand }, }); // Send the email transporter.sendMail( { from: "sender@example.com", to: ["recipient@example.com"], subject: "Message via SES transport", text: "I hope this message gets sent!", ses: { // Add tags for tracking and analytics EmailTags: [{ Name: "tag_name", Value: "tag_value" }], }, }, (err, info) => { if (err) { console.error("Failed to send email:", err); return; } console.log("Email sent successfully!"); console.log("Envelope:", info.envelope); console.log("Message ID:", info.messageId); } ); ``` -------------------------------- ### Plugin Error Handling Example Source: https://nodemailer.com/plugins If a plugin encounters an error that should prevent the message from being sent, pass an `Error` object to the callback. This error will be returned to the caller. ```javascript callback(new Error("Template not found")); ``` -------------------------------- ### Request Success Notification Source: https://nodemailer.com/message/dsn Request a notification when the message is successfully delivered. This example configures the DSN object with an ID, return type, and success notification. ```javascript const nodemailer = require("nodemailer"); const transporter = nodemailer.createTransport({ host: "smtp.example.com", port: 587, secure: false, auth: { user: "smtp-user", pass: "smtp-pass", }, }); await transporter.sendMail({ from: "sender@example.com", to: "recipient@example.com", subject: "Message", text: "I hope this message gets read!", dsn: { id: "msg-123", return: "headers", notify: "success", recipient: "sender@example.com", }, }); ``` -------------------------------- ### Internationalized Domain Name (IDN) Source: https://nodemailer.com/message/addresses Nodemailer automatically converts Unicode domains to their Punycode ASCII-compatible encoding. This example shows a Unicode domain that will be converted. ```plaintext "андрис@уайлддак.орг" ``` -------------------------------- ### Connect to SMTP Server Source: https://nodemailer.com/extras/smtp-connection Establish a connection to the SMTP server. The callback is invoked when the connection is ready for commands after the initial handshake. ```javascript connection.connect((err) => { if (err) { console.error("Connection failed:", err); return; } console.log("Connected!"); }); ``` -------------------------------- ### Example: Replace Tabs with Spaces in Stream Source: https://nodemailer.com/plugins/create A 'stream' plugin that inserts a transform stream to replace all tab characters with spaces in the outgoing message data before it is sent. ```javascript const { Transform } = require("stream"); const tabToSpace = new Transform(); tabToSpace._transform = function (chunk, _enc, cb) { for (let i = 0; i < chunk.length; ++i) { if (chunk[i] === 0x09) chunk[i] = 0x20; // 0x09 = TAB, 0x20 = space } this.push(chunk); cb(); }; transporter.use("stream", (mail, done) => { mail.message.transform(tabToSpace); done(); }); ``` -------------------------------- ### Send Raw SMTP Command (Callback Style) Source: https://nodemailer.com/smtp/customauth Use `ctx.sendCommand` with a callback to send a raw SMTP command and process the server's response. This is an alternative to using Promises for handling authentication. ```javascript ctx.sendCommand(command, (err, response) => { if (err) { return ctx.reject(err); } // Process response... ctx.resolve(); }); ``` -------------------------------- ### Create SMTPConnection Instance Source: https://nodemailer.com/extras/smtp-connection Create a new instance of SMTPConnection with specified options. ```javascript const connection = new SMTPConnection(options); ``` -------------------------------- ### Registering a Compile Plugin Source: https://nodemailer.com/plugins Register a compile plugin on a transport instance using the `use()` method. This plugin will run before MIME generation. ```javascript const nodemailer = require("nodemailer"); const transport = nodemailer.createTransport({ sendmail: true }); // Register a compile plugin - it will run before MIME generation transport.use("compile", require("./myCompilePlugin")); ``` -------------------------------- ### Verify SMTP Configuration with Callbacks Source: https://nodemailer.com/smtp Test your SMTP configuration using `transporter.verify()` with callbacks. This method checks DNS resolution, TCP connection, TLS upgrade, and authentication. ```javascript // Using callbacks transporter.verify((error, success) => { if (error) { console.error(error); } else { console.log("Server is ready to take our messages"); } }); ``` -------------------------------- ### Example SMTP Responses with Enhanced Status Codes Source: https://nodemailer.com/extras/smtp-server Illustrates the format of SMTP responses when enhanced status codes are enabled. These codes provide more detailed information about the success or failure of an SMTP command. ```text 250 2.1.0 Accepted <- Enhanced status code: 2.1.0 550 5.1.1 Mailbox unavailable <- Enhanced status code: 5.1.1 ``` -------------------------------- ### Handle Authentication Attempts Source: https://nodemailer.com/extras/smtp-server Implement the `onAuth` callback to verify client credentials and accept or reject login attempts. Supports various authentication methods. ```javascript const server = new SMTPServer({ onAuth(auth, session, callback) { // auth.method contains the authentication method: 'PLAIN', 'LOGIN', 'XOAUTH2', or 'CRAM-MD5' // Call callback(err) to reject, or callback(null, { user: ... }) to accept }, }); ``` -------------------------------- ### Stream Message with Windows Line Endings Source: https://nodemailer.com/transports/stream This example demonstrates generating an email as a readable stream using Windows-style CRLF line endings. The generated stream can be piped to any writable destination, such as process.stdout. ```javascript const nodemailer = require("nodemailer"); const transporter = nodemailer.createTransport({ streamTransport: true, newline: "windows", // Use CRLF (\r\n) line endings }); transporter.sendMail( { from: "sender@example.com", to: "recipient@example.com", subject: "Streamed message", text: "This message is streamed using CRLF line endings.", }, (err, info) => { if (err) throw err; console.log(info.envelope); // { from: '...', to: ['...'] } console.log(info.messageId); // '' // Pipe the raw RFC 822 message to stdout info.message.pipe(process.stdout); } ); ``` -------------------------------- ### Local Testing with SSH SOCKS Proxy Source: https://nodemailer.com/smtp/proxies Set up a local SOCKS5 proxy for testing using SSH dynamic port forwarding. This command creates a proxy listening on port 1080, which can then be used by Nodemailer. ```bash ssh -N -D 0.0.0.0:1080 user@remote.host ``` -------------------------------- ### Complete Example: Custom SMTP Envelope Source: https://nodemailer.com/smtp/envelope Demonstrates sending an email with a custom SMTP envelope, overriding the default behavior. The 'envelope' property is used to set specific 'MAIL FROM' and 'RCPT TO' addresses. ```javascript const nodemailer = require("nodemailer"); async function main() { // Create a transport (replace with your own transport options) const transport = nodemailer.createTransport({ sendmail: true, }); const info = await transport.sendMail({ from: "Mailer ", // Visible From: header to: "Daemon ", // Visible To: header envelope: { from: "bounce+12345@example.com", // Actual MAIL FROM (for bounces) to: [ // Actual RCPT TO recipients (who really receive the email) "daemon@example.com", "mailer@example.com", ], }, subject: "Custom SMTP envelope", text: "Hello!", }); console.log("Envelope used:", info.envelope); // => { from: 'bounce+12345@example.com', to: [ 'daemon@example.com', 'mailer@example.com' ] } } main().catch(console.error); ``` -------------------------------- ### Configure Transport with Multiple DKIM Keys Source: https://nodemailer.com/dkim Configure Nodemailer to sign messages with multiple DKIM keys, useful for key rotation or signing for different subdomains. Disk caching is disabled in this example. ```javascript const transporter = nodemailer.createTransport({ host: "smtp.example.com", port: 465, secure: true, dkim: { keys: [ { domainName: "example.com", keySelector: "2017", privateKey: fs.readFileSync("./dkim-2017.pem", "utf8"), }, { domainName: "example.com", keySelector: "2016", privateKey: fs.readFileSync("./dkim-2016.pem", "utf8"), }, ], cacheDir: false, // disable disk caching }, }); ``` -------------------------------- ### Validate Client Connections Source: https://nodemailer.com/extras/smtp-server Use `onConnect` to accept or reject incoming connections based on criteria like IP address. Use `onClose` for connection cleanup. ```javascript const server = new SMTPServer({ onConnect(session, callback) { if (session.remoteAddress === "127.0.0.1") { return callback(new Error("Connections from localhost are not allowed")); } callback(); // Accept the connection }, onClose(session) { console.log(`Connection from ${session.remoteAddress} closed`); }, }); ``` -------------------------------- ### Create Readable Stream for Email Source: https://nodemailer.com/extras/mailcomposer Use createReadStream() to get a readable stream of the raw RFC 822 message. This is efficient for piping directly to other streams without loading the entire message into memory. ```javascript const mail = new MailComposer({ from: "you@example.com" /* ... */ }); const stream = mail.compile().createReadStream(); stream.pipe(process.stdout); ``` -------------------------------- ### Send Email and Get Preview URL Source: https://nodemailer.com/guides/testing-with-ethereal Sends an email using a configured transporter and retrieves a URL to preview the sent message in the Ethereal web interface. Useful for debugging email content. ```javascript const info = await transporter.sendMail({ from: "Test Sender" ", to: "recipient@example.com", subject: "Test Email", text: "This is a test email sent via Ethereal!", html: "

This is a test email sent via Ethereal!

", }); console.log("Message sent: %s", info.messageId); // Get the Ethereal URL to preview this email const previewUrl = nodemailer.getTestMessageUrl(info); console.log("Preview URL: %s", previewUrl); // Output: https://ethereal.email/message/... ``` -------------------------------- ### Use Custom Iconv Implementation Source: https://nodemailer.com/extras/mailparser To use a different iconv implementation (e.g., node-iconv) for character set conversion, inject it via the 'Iconv' option when calling simpleParser. ```javascript const { Iconv } = require("iconv"); const { simpleParser } = require("mailparser"); simpleParser(rfc822Message, { Iconv }) .then((mail) => { console.log(mail.subject); }); ```