UNPKG

@visulima/email

Version:

A comprehensive email library with multi-provider support, crypto utilities, and template engines

358 lines (357 loc) 13.7 kB
import type { AttachmentDataOptions, AttachmentOptions } from './attachment-helpers.d.ts'; import type { EmailEncrypter, EmailSigner } from './crypto/index.d.ts'; import type { Provider } from './providers/provider.d.ts'; import type { TemplateRenderer } from './template-engines/types.d.ts'; import type { EmailAddress, EmailHeaders, EmailOptions, EmailResult, Priority, Receipt, Result } from './types.d.ts'; type AddressInput = EmailAddress | EmailAddress[] | string | string[]; /** * Mailable interface - represents an email that can be sent. */ export interface Mailable { /** * Builds the email message. */ build: () => Promise<EmailOptions>; } /** * Mail message builder - provides fluent interface for building emails. */ export declare class MailMessage { private fromAddress?; private toAddresses; private ccAddresses; private bccAddresses; private subjectText; private textContent?; private autoTextEnabled; private htmlContent?; private headers; private attachments; private replyToAddress?; private priorityValue?; private tagsValue; private provider?; private signer?; private encrypter?; private logger?; /** * Sets the sender address. * @param address The sender email address (string or EmailAddress object). * @returns This instance for method chaining. */ from(address: EmailAddress | string): this; /** * Sets the recipient address(es). * @param address The recipient email address(es) (string, EmailAddress, or arrays of either). * @returns This instance for method chaining. */ to(address: AddressInput): this; /** * Sets the CC recipient address(es). * @param address The CC recipient email address(es) (string, EmailAddress, or arrays of either). * @returns This instance for method chaining. */ cc(address: AddressInput): this; /** * Sets the BCC recipient address(es). * @param address The BCC recipient email address(es) (string, EmailAddress, or arrays of either). * @returns This instance for method chaining. */ bcc(address: AddressInput): this; /** * Sets the subject line for the email message. * @param text The subject text to set. * @returns This instance for method chaining. */ subject(text: string): this; /** * Sets the plain text content of the email. * @param content The plain text content to set. * @returns This instance for method chaining. */ text(content: string): this; /** * Sets the HTML content of the email. * @param content The HTML content to set. * @returns This instance for method chaining. */ html(content: string): this; /** * Sets a custom email header. * @param name The header name to set. * @param value The header value to set. * @returns This instance for method chaining. */ header(name: string, value: string): this; /** * Sets multiple headers. * Accepts both Record&lt;string, string> and ImmutableHeaders. * @param headers The headers to set (Record or ImmutableHeaders). * @returns This instance for method chaining. */ setHeaders(headers: EmailHeaders): this; /** * Attaches a file from path (reads file from filesystem). * Similar to Laravel's attach() method. * @param filePath The absolute or relative filesystem path to the file to attach. * @param options Optional attachment configuration (filename, contentType, etc.). * @returns This instance for method chaining. * @example * ```ts * message.attachFromPath('/path/to/file.pdf') * message.attachFromPath('/path/to/file.pdf', { filename: 'custom-name.pdf' }) * ``` */ attachFromPath(filePath: string, options?: AttachmentOptions): Promise<this>; /** * Attaches raw data (string or Buffer). * Similar to Laravel's attachData() method. * @param content The content to attach (string or Buffer). * @param options Attachment options including filename. * @returns This instance for method chaining. * @example * ```ts * message.attachData(Buffer.from('content'), 'file.txt') * message.attachData('content', 'file.txt', { contentType: 'text/plain' }) * ``` */ attachData(content: string | Buffer, options: AttachmentDataOptions): this; /** * Embeds an inline attachment from file path (for images in HTML). * Similar to Laravel's embed() method. * Returns the Content-ID that can be used in HTML: &lt;img src="cid:{cid}">. * @param filePath The path to the file to embed. * @param options Optional attachment options (filename, contentType, etc.). * @returns The Content-ID string that can be used in HTML. * @example * ```ts * const cid = await message.embedFromPath('/path/to/logo.png') * message.html(`<img src="cid:${cid}">`) * ``` */ embedFromPath(filePath: string, options?: Omit<AttachmentOptions, "contentDisposition" | "cid">): Promise<string>; /** * Embeds raw data as inline attachment (for images in HTML). * Similar to Laravel's embedData() method. * Returns the Content-ID that can be used in HTML: &lt;img src="cid:{cid}">. * @param content The content to embed (string or Buffer). * @param filename The filename for the embedded attachment. * @param options Optional attachment options (contentType, etc.). * @returns The Content-ID string that can be used in HTML. * @example * ```ts * const imageBuffer = Buffer.from('...') * const cid = message.embedData(imageBuffer, 'logo.png', { contentType: 'image/png' }) * message.html(`<img src="cid:${cid}">`) * ``` */ embedData(content: string | Buffer, filename: string, options?: Omit<AttachmentDataOptions, "filename" | "contentDisposition" | "cid">): string; /** * Sets the reply-to address. * @param address The reply-to email address (string or EmailAddress object). * @returns This instance for method chaining. */ replyTo(address: EmailAddress | string): this; /** * Sets the email priority. * @param priority The priority level ('high', 'normal', or 'low'). * @returns This instance for method chaining. */ priority(priority: Priority): this; /** * Sets email tags for categorization. * @param tags The tags to set (string or array of strings). * @returns This instance for method chaining. */ tags(tags: string | string[]): this; /** * Sets the provider to use for sending. * @param provider The email provider instance. * @returns This instance for method chaining. */ mailer(provider: Provider): this; /** * Signs the email message using a signer (DKIM or S/MIME). * @param signer The signer instance to use. * @example * ```ts * import { createDkimSigner } from '@visulima/email/crypto'; * const signer = createDkimSigner({ * domainName: 'example.com', * keySelector: 'default', * privateKey: '-----BEGIN PRIVATE KEY-----...' * }); * message.sign(signer) * ``` */ sign(signer: EmailSigner): this; /** * Encrypts the email message using an encrypter (S/MIME). * @param encrypter The encrypter instance to use. * @example * ```ts * import { createSmimeEncrypter } from '@visulima/email/crypto'; * const encrypter = createSmimeEncrypter({ * certificates: '/path/to/certificate.crt' * }); * message.encrypt(encrypter) * ``` */ encrypt(encrypter: EmailEncrypter): this; /** * Sets the logger instance for this message. * @param logger The logger instance (Console) to use for logging. * @returns This instance for method chaining. * @example * ```ts * message.logger(console) * ``` */ setLogger(logger: Console): this; /** * Renders a template and sets as HTML content. * Accepts a render function for flexible template engine support. * @param render The template renderer function. * @param template The template content (string, React component, etc.). * @param data Optional data/variables to pass to the template. * @param options Optional renderer-specific options. * @param options.autoText Whether to auto-generate text version from HTML (default: true). * @returns This instance for method chaining. * @example * ```ts * import { renderHandlebars } from '@visulima/email/template/handlebars'; * message.view(renderHandlebars, '<h1>Hello {{name}}!</h1>', { name: 'John' }) * * import { renderMjml } from '@visulima/email/template/mjml'; * message.view(renderMjml, mjmlTemplate) * * import { renderReactEmail } from '@visulima/email/template/react-email'; * message.view(renderReactEmail, <WelcomeEmail name="John" />) * ``` */ view(render: TemplateRenderer, template: unknown, data?: Record<string, unknown>, options?: { [key: string]: unknown; autoText?: boolean; }): Promise<this>; /** * Renders a text template and sets as text content. * @param render The template renderer function. * @param template The text template content. * @param data Optional data/variables to pass to the template. * @param options Optional renderer-specific options. * @returns This instance for method chaining. * @example * ```ts * import { renderHandlebars } from '@visulima/email/template/handlebars'; * message.viewText(renderHandlebars, 'Hello {{name}}!', { name: 'John' }) * ``` */ viewText(render: TemplateRenderer, template: string, data?: Record<string, unknown>, options?: Record<string, unknown>): Promise<this>; /** * Builds the email options. * @returns The built email options ready for sending. * @throws {Error} When required fields (from, to, subject, content) are missing. */ build(): Promise<EmailOptions>; /** * Sends the email. * @returns A result object containing the email result or error. * @throws {Error} When no provider is configured. */ send(): Promise<Result<EmailResult>>; /** * Attempts to auto-generate text content from HTML. * @param html The HTML content to convert. * @private */ private tryAutoGenerateText; /** * Creates an error, logs it, and throws it. * @param message Error message to throw. * @param logMessage Optional log message (defaults to message). * @private */ private throwAndLogError; } /** * Mail class - instance-based email sending. */ export declare class Mail { /** * Extracts error messages from an error object. * @param error Error object to extract messages from. * @returns Array of error messages. * @private */ private static extractErrorMessages; private provider; private logger?; private loggerInstance?; /** * Creates a new Mail instance with a provider. * @param provider The email provider instance. */ constructor(provider: Provider); /** * Sets the logger instance for this mail instance. * The logger will be passed to all MailMessage instances created via message(). * @param logger The logger instance (Console) to use for logging. * @returns This instance for method chaining. * @example * ```ts * const mail = createMail(provider); * mail.setLogger(console); * ``` */ setLogger(logger: Console): this; /** * Creates a new mail message. * @returns A new MailMessage instance configured with this provider. */ message(): MailMessage; /** * Sends a mailable instance. * @param mailable The mailable instance to send. * @returns A result object containing the email result or error. */ send(mailable: Mailable): Promise<Result<EmailResult>>; /** * Sends email using email options directly. * @param options The email options to send. * @returns A result object containing the email result or error. */ sendEmail(options: EmailOptions): Promise<Result<EmailResult>>; /** * Sends multiple messages using the email service. * Returns an async iterable that yields receipts for each sent message. * @example * ```ts * const messages = [ * { from: "sender@example.com", to: "user1@example.com", subject: "Hello 1", html: "<h1>Hello</h1>" }, * { from: "sender@example.com", to: "user2@example.com", subject: "Hello 2", html: "<h1>Hello</h1>" }, * ]; * * for await (const receipt of mail.sendMany(messages)) { * if (receipt.successful) { * console.log("Sent:", receipt.messageId); * } else { * console.error("Failed:", receipt.errorMessages); * } * } * ``` * @param messages An iterable of email options or mailables to send. * @param options Optional parameters for sending. * @param options.signal Abort signal to cancel the operation. * @returns An async iterable that yields receipts for each sent message. */ sendMany(messages: Iterable<EmailOptions | Mailable> | AsyncIterable<EmailOptions | Mailable>, options?: { signal?: AbortSignal; }): AsyncIterable<Receipt>; } /** * Creates a new Mail instance with a provider. * @param provider The email provider instance. * @returns A new Mail instance. */ export declare const createMail: (provider: Provider) => Mail; export {};