### Install Dependencies Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Installs project dependencies using pnpm. Ensure pnpm is installed globally. ```bash pnpm install ``` -------------------------------- ### Run Integration Tests Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Starts the development server for integration testing using wrangler. Send POST requests to the specified local address. ```bash pnpm dlx wrangler dev ./test/worker.ts ``` -------------------------------- ### Install Worker Mailer Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Install the worker-mailer package using npm. ```shell npm i worker-mailer ``` -------------------------------- ### Quick Start: Connect and Send Email Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Connect to an SMTP server and send an email using Worker Mailer. Ensure your wrangler.toml is configured. ```typescript import { WorkerMailer } from 'worker-mailer' // Connect to SMTP server const mailer = await WorkerMailer.connect({ credentials: { username: 'bob@acme.com', password: 'password', }, authType: 'plain', host: 'smtp.acme.com', port: 587, secure: true, }) // Send email await mailer.send({ from: { name: 'Bob', email: 'bob@acme.com' }, to: { name: 'Alice', email: 'alice@acme.com' }, subject: 'Hello from Worker Mailer', text: 'This is a plain text message', html: '
This is an HTML message
', }) ``` -------------------------------- ### Cloudflare Worker Mailer Integration Example Source: https://context7.com/zou-yu/worker-mailer/llms.txt This example demonstrates how to set up and use Worker Mailer within a Cloudflare Worker. It requires specific environment variables for SMTP configuration and includes basic error handling. Ensure `nodejs_compat` is enabled in your wrangler.toml. ```typescript // wrangler.toml configuration required: // compatibility_flags = ["nodejs_compat"] import { WorkerMailer, LogLevel } from 'worker-mailer' interface Env { SMTP_HOST: string SMTP_PORT: string SMTP_USERNAME: string SMTP_PASSWORD: string } export default { async fetch(request: Request, env: Env): Promise${message}
` }) await mailer.close() return new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json' } }) } catch (error) { console.error('Email error:', error) return new Response( JSON.stringify({ error: 'Failed to send email' }), { status: 500, headers: { 'Content-Type': 'application/json' } } ) } } } ``` -------------------------------- ### WorkerMailer.send() Static Method Example Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Demonstrates sending a one-off email using the static WorkerMailer.send() method. Requires WorkerMailer options and EmailOptions. ```typescript await WorkerMailer.send( { // WorkerMailerOptions host: 'smtp.acme.com', port: 587, credentials: { username: 'user', password: 'pass', }, }, { // EmailOptions from: 'sender@acme.com', to: 'recipient@acme.com', subject: 'Test', text: 'Hello', attachments: [ { filename: 'test.txt', content: 'SGVsbG8gV29ybGQ=', // base64-encoded string for "Hello World" type: 'text/plain', }, ], }, ) ``` -------------------------------- ### Integration Test Request Body Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Example JSON payload for integration testing via POST request to the local development server. ```json { "config": { "credentials": { "username": "xxx@xx.com", "password": "xxxx" }, "authType": "plain", "host": "smtp.acme.com", "port": 587, "secure": false, "startTls": true }, "email": { "from": "xxx@xx.com", "to": "yyy@yy.com", "subject": "Test Email", "text": "Hello World" } } ``` -------------------------------- ### Framework Integration with Conditional Imports Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Example for integrating Worker Mailer with modern JavaScript frameworks like Nuxt.js, using conditional dynamic imports for development and production environments. ```typescript export default defineEventHandler(async event => { // Check if running in development environment if (import.meta.dev) { // Development: Use nodemailer (or any Node.js compatible email library) const nodemailer = await import('nodemailer') const transporter = nodemailer.default.createTransport() return await transporter.sendMail() } else { // Production: Use worker-mailer in Cloudflare Workers environment const { WorkerMailer } = await import('worker-mailer') const mailer = await WorkerMailer.connect() return await mailer.send() } }) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Executes the unit tests for the project using npm. ```bash npm test ``` -------------------------------- ### Configuration: LogLevel and Authentication Source: https://context7.com/zou-yu/worker-mailer/llms.txt Details on configuring logging verbosity and SMTP authentication methods. ```APIDOC ## LogLevel Enum ### Description Configures the verbosity of internal logging for debugging SMTP communication. - **DEBUG** (0): All messages including SMTP protocol details - **INFO** (1): Connection status and key events (default) - **WARN** (2): Warnings only - **ERROR** (3): Errors only - **NONE** (4): No logging ## Authentication Types ### Description Worker Mailer supports three SMTP authentication methods: PLAIN, LOGIN, and CRAM-MD5. You can specify a single method or provide an array of preferred methods in priority order. ``` -------------------------------- ### WorkerMailer.connect() Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Establishes a connection to an SMTP server. This is the primary method for initializing the Worker Mailer client. ```APIDOC ## WorkerMailer.connect(options) ### Description Creates a new SMTP connection. ### Method `WorkerMailer.connect` ### Parameters #### Request Body - **options** (WorkerMailerOptions) - Required - Configuration options for the SMTP connection. ```typescript type WorkerMailerOptions = { host: string // SMTP server hostname port: number // SMTP server port (usually 587 or 465) secure?: boolean // Use TLS (default: false) startTls?: boolean // Upgrade to TLS if SMTP server supports (default: true) credentials?: { // SMTP authentication credentials username: string password: string } authType?: | 'plain' | 'login' | 'cram-md5' | Array<'plain' | 'login' | 'cram-md5'> logLevel?: LogLevel // Logging level (default: LogLevel.INFO) socketTimeoutMs?: number // Socket timeout in milliseconds responseTimeoutMs?: number // Server response timeout in milliseconds dsn?: { RET?: { HEADERS?: boolean FULL?: boolean } NOTIFY?: { DELAY?: boolean FAILURE?: boolean SUCCESS?: boolean } } } ``` ### Response #### Success Response (200) - **mailer** (WorkerMailer) - An instance of the WorkerMailer client connected to the SMTP server. #### Response Example ```typescript const mailer = await WorkerMailer.connect({ credentials: { username: 'bob@acme.com', password: 'password', }, authType: 'plain', host: 'smtp.acme.com', port: 587, secure: true, }) ``` ``` -------------------------------- ### Connect to SMTP Server Source: https://context7.com/zou-yu/worker-mailer/llms.txt Initializes a persistent SMTP connection with authentication and configuration options. ```typescript import { WorkerMailer, LogLevel } from 'worker-mailer' // Connect to SMTP server with full configuration const mailer = await WorkerMailer.connect({ host: 'smtp.example.com', port: 587, secure: false, // Use implicit TLS (port 465) startTls: true, // Upgrade to TLS via STARTTLS (default: true) credentials: { username: 'user@example.com', password: 'your-password' }, authType: 'plain', // Options: 'plain', 'login', 'cram-md5', or array logLevel: LogLevel.INFO, // Options: DEBUG, INFO, WARN, ERROR, NONE socketTimeoutMs: 60000, // Socket connection timeout (default: 60s) responseTimeoutMs: 30000, // Server response timeout (default: 30s) dsn: { // Delivery Status Notification settings RET: { HEADERS: true }, // Return headers on bounce NOTIFY: { SUCCESS: true, FAILURE: true, DELAY: true } } }) // Connection is now ready - send multiple emails await mailer.send({ /* email options */ }) await mailer.send({ /* another email */ }) // Close connection when done await mailer.close() ``` -------------------------------- ### Configure Wrangler.toml Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Configure your wrangler.toml file to enable Node.js compatibility for Worker Mailer. ```toml compatibility_flags = ["nodejs_compat"] ``` ```toml # or compatibility_flags = ["nodejs_compat_v2"] ``` -------------------------------- ### WorkerMailer.connect(options) Source: https://context7.com/zou-yu/worker-mailer/llms.txt Establishes and initializes a new SMTP connection. This method handles the SMTP handshake, capability negotiation, TLS upgrade, and authentication, creating a persistent connection for efficient email sending. ```APIDOC ## WorkerMailer.connect(options) ### Description Creates and initializes a new SMTP connection to the mail server. This method establishes a persistent connection that can be reused for sending multiple emails efficiently. It handles the SMTP handshake, capability negotiation, TLS upgrade (if configured), and authentication automatically. ### Method `WorkerMailer.connect` ### Parameters #### Options Object - **host** (string) - Required - The SMTP server hostname. - **port** (number) - Optional - The SMTP server port (default: 25). - **secure** (boolean) - Optional - Use implicit TLS (port 465). Default is false. - **startTls** (boolean) - Optional - Upgrade to TLS via STARTTLS. Default is true. - **credentials** (object) - Required - An object containing `username` and `password` for authentication. - **username** (string) - Required - The username for SMTP authentication. - **password** (string) - Required - The password for SMTP authentication. - **authType** (string) - Optional - The authentication method. Options: 'plain', 'login', 'cram-md5', or an array of types. Default is 'plain'. - **logLevel** (LogLevel) - Optional - The logging level. Options: DEBUG, INFO, WARN, ERROR, NONE. Default is INFO. - **socketTimeoutMs** (number) - Optional - Socket connection timeout in milliseconds. Default is 60000. - **responseTimeoutMs** (number) - Optional - Server response timeout in milliseconds. Default is 30000. - **dsn** (object) - Optional - Delivery Status Notification settings. - **RET** (object) - Optional - Specifies what to return on bounce. - **HEADERS** (boolean) - Optional - Return headers on bounce. - **NOTIFY** (object) - Optional - Specifies when to send notifications. - **SUCCESS** (boolean) - Optional - Notify on success. - **FAILURE** (boolean) - Optional - Notify on failure. - **DELAY** (boolean) - Optional - Notify on delay. ### Request Example ```typescript import { WorkerMailer, LogLevel } from 'worker-mailer' const mailer = await WorkerMailer.connect({ host: 'smtp.example.com', port: 587, startTls: true, credentials: { username: 'user@example.com', password: 'your-password' }, authType: 'plain', logLevel: LogLevel.INFO, dsn: { RET: { HEADERS: true }, NOTIFY: { SUCCESS: true, FAILURE: true, DELAY: true } } }) ``` ### Response #### Success Response (200) - **mailer** (WorkerMailer) - An instance of the WorkerMailer client with an active connection. ``` -------------------------------- ### mailer.send(options) Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Sends an email using the configured mailer instance. ```APIDOC ## mailer.send(options) ### Description Sends an email using the current mailer instance configuration. ### Parameters #### Request Body - **from** (string|object) - Required - Sender's email address or object with name and email. - **to** (string|string[]|object|array) - Required - Recipient(s) email address(es). - **reply** (string|object) - Optional - Reply-To address. - **cc** (string|string[]|object|array) - Optional - Carbon Copy recipients. - **bcc** (string|string[]|object|array) - Optional - Blind Carbon Copy recipients. - **subject** (string) - Required - Email subject. - **text** (string) - Optional - Plain text content. - **html** (string) - Optional - HTML content. - **headers** (RecordThis is an HTML message
', attachments: [ { filename: 'notes.txt', content: 'Some notes here', }, ], }) ``` ``` -------------------------------- ### Configure Logging Verbosity with LogLevel Source: https://context7.com/zou-yu/worker-mailer/llms.txt Set the logLevel option during connection to control internal logging. DEBUG shows all SMTP details, while ERROR or NONE are suitable for production. ```typescript import { WorkerMailer, LogLevel } from 'worker-mailer' // Available log levels (in order of verbosity) // LogLevel.DEBUG = 0 - All messages including SMTP protocol details // LogLevel.INFO = 1 - Connection status and key events (default) // LogLevel.WARN = 2 - Warnings only // LogLevel.ERROR = 3 - Errors only // LogLevel.NONE = 4 - No logging // Debug mode for troubleshooting SMTP issues const mailer = await WorkerMailer.connect({ host: 'smtp.example.com', port: 587, credentials: { username: 'user@example.com', password: 'password' }, authType: 'plain', logLevel: LogLevel.DEBUG // Shows all SMTP commands and responses }) // Production mode - minimal logging const prodMailer = await WorkerMailer.connect({ host: 'smtp.example.com', port: 587, credentials: { username: 'user@example.com', password: 'password' }, authType: 'plain', logLevel: LogLevel.ERROR // Only log errors }) ``` -------------------------------- ### Send Email via SMTP Source: https://context7.com/zou-yu/worker-mailer/llms.txt Sends an email using an established connection, supporting attachments, custom headers, and DSN overrides. ```typescript import { WorkerMailer } from 'worker-mailer' const mailer = await WorkerMailer.connect({ host: 'smtp.example.com', port: 587, credentials: { username: 'sender@example.com', password: 'password' }, authType: 'plain' }) // Send email with all options await mailer.send({ // Sender - string or object format from: { name: 'John Doe', email: 'john@example.com' }, // Recipients - supports string, array, or object format to: [ { name: 'Alice Smith', email: 'alice@example.com' }, 'bob@example.com' ], // Optional CC and BCC recipients cc: { name: 'Manager', email: 'manager@example.com' }, bcc: ['audit@example.com', 'archive@example.com'], // Reply-To address reply: { name: 'Support Team', email: 'support@example.com' }, // Subject line subject: 'Monthly Report - March 2024', // Content - at least one of text or html required text: 'Please find the monthly report attached.', html: `Please find the monthly report attached.
Best regards,
John
Please find the monthly report attached.
Best regards,
John
Thank you for signing up!
' } ) ``` -------------------------------- ### mailer.close Source: https://context7.com/zou-yu/worker-mailer/llms.txt Gracefully terminates the SMTP connection. ```APIDOC ## mailer.close(error?) ### Description Gracefully closes the SMTP connection by sending the QUIT command. If called with an error parameter, it will reject all pending emails in the queue with that error. ### Parameters - **error** (Error) - Optional - Error object to reject pending emails with. ``` -------------------------------- ### WorkerMailer.send() Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Static method to send a one-off email without maintaining a persistent connection. ```APIDOC ## WorkerMailer.send() ### Description Send a one-off email without maintaining the connection. ### Request Example await WorkerMailer.send( { host: 'smtp.acme.com', port: 587, credentials: { username: 'user', password: 'pass', }, }, { from: 'sender@acme.com', to: 'recipient@acme.com', subject: 'Test', text: 'Hello', attachments: [ { filename: 'test.txt', content: 'SGVsbG8gV29ybGQ=', type: 'text/plain', }, ], }, ) ``` -------------------------------- ### EmailOptions Type Definition Source: https://github.com/zou-yu/worker-mailer/blob/main/README.md Defines the structure for email options, including sender, recipients, subject, content, and attachments. Ensure attachment content is base64-encoded. ```typescript type EmailOptions = { from: | string | { // Sender's email name?: string email: string } to: | string | string[] | { // Recipients (TO) name?: string email: string } | Array<{ name?: string; email: string }> reply?: | string | { // Reply-To address name?: string email: string } cc?: | string | string[] | { // Carbon Copy recipients name?: string email: string } | Array<{ name?: string; email: string }> bcc?: | string | string[] | { // Blind Carbon Copy recipients name?: string email: string } | Array<{ name?: string; email: string }> subject: string // Email subject text?: string // Plain text content html?: string // HTML content headers?: Record