### Implement OrderConfirmationMail Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Example of using the prepare method to configure email recipients and templates. ```typescript class OrderConfirmationMail extends BaseMail { prepare() { this.message .to(this.user.email) .subject(this.subject) .htmlView('emails/order-confirmation', { order: this.order }) } } ``` -------------------------------- ### Multi-Transport Configuration Example Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/transports.md Configures multiple mailers within the defineConfig function, demonstrating SMTP, Postmark, Mailgun, and SES setups. ```typescript export default defineConfig({ default: 'smtp', mailers: { // Primary transactional emails smtp: transports.smtp({ host: process.env.SMTP_HOST, port: process.env.SMTP_PORT, auth: { type: 'login', user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD } }), // Reliable delivery for important emails postmark: transports.postmark({ key: process.env.POSTMARK_TOKEN, baseUrl: 'https://api.postmarkapp.com' }), // Marketing and bulk emails mailgun: transports.mailgun({ key: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN }), // AWS infrastructure ses: transports.ses({ region: process.env.AWS_REGION, credentials: { accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_KEY } }) }, from: { address: 'noreply@example.com', name: 'My App' } }) ``` -------------------------------- ### Configure Mailers with Transports Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Example of setting up SMTP and Postmark mailers using the defineConfig helper. ```typescript export default defineConfig({ default: 'smtp', mailers: { smtp: transports.smtp({ host: process.env.SMTP_HOST, port: process.env.SMTP_PORT, secure: true, auth: { type: 'login', user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD } }), postmark: transports.postmark({ key: process.env.POSTMARK_TOKEN, baseUrl: 'https://api.postmarkapp.com' }) } }) ``` -------------------------------- ### Define Global Reply-To Address Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Configuration schema and example for setting the default reply-to address. ```typescript replyTo?: { address: string name?: string } | string ``` ```typescript export default defineConfig({ replyTo: 'support@example.com' }) ``` -------------------------------- ### Brevo Transport Configuration Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/transports.md Defines the configuration schema and example setup for the Brevo transport. ```typescript { key: string // Brevo API key baseUrl: string // API base URL (e.g., https://api.brevo.com) scheduledAt?: Date // Schedule send time tags?: string[] // Email tags } ``` ```typescript export default defineConfig({ default: 'brevo', mailers: { brevo: transports.brevo({ key: process.env.BREVO_API_KEY, baseUrl: 'https://api.brevo.com' }) } }) ``` -------------------------------- ### Install AdonisJS Mail Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/README.md Commands to install the package and configure it using the Ace CLI. ```bash npm install @adonisjs/mail node ace add @adonisjs/mail ``` -------------------------------- ### SparkPost Transport Configuration Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/transports.md Defines the configuration schema and example setup for the SparkPost transport. ```typescript { key: string // SparkPost API key baseUrl: string // API base URL startTime?: Date // Scheduled send time initialOpen?: boolean // Track initial open openTracking?: boolean // Enable open tracking clickTracking?: boolean // Enable click tracking transactional?: boolean // Mark as transactional sandbox?: boolean // Sandbox mode skipSuppression?: boolean // Skip suppression list ipPool?: string // IP pool name } ``` ```typescript export default defineConfig({ default: 'sparkpost', mailers: { sparkpost: transports.sparkpost({ key: process.env.SPARKPOST_API_KEY, baseUrl: 'https://api.sparkpost.com', openTracking: true, clickTracking: true }) } }) ``` -------------------------------- ### Handle E_INVALID_CONFIG Errors Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/errors.md Examples demonstrating how to catch and handle configuration errors when sending mail or accessing mailers. ```typescript import { errors } from '@adonisjs/mail' try { await mail.send((message) => { message.to('user@example.com').subject('Test') }) } catch (error) { if (error.code === 'E_INVALID_CONFIG') { console.error('Invalid mail configuration:', error.message) } } ``` ```typescript import { MailManager } from '@adonisjs/mail' import { errors } from '@adonisjs/mail' const mailManager = new MailManager(emitter, config) try { const mailer = mailManager.use('nonexistent') } catch (error) { if (error instanceof errors.E_INVALID_CONFIG) { console.error('Configuration error:', error.message) } } ``` -------------------------------- ### Postmark Transport Configuration Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/transports.md Defines the configuration schema and example setup for the Postmark transport. ```typescript { key: string // Postmark server token baseUrl: string // API base URL (e.g., https://api.postmarkapp.com) messageStream?: string // Message stream ID tag?: string // Message tag trackOpens?: boolean // Track opens trackLinks?: 'None' | 'HtmlAndText' | 'HtmlOnly' | 'TextOnly' metadata?: Record // Custom metadata } ``` ```typescript export default defineConfig({ default: 'postmark', mailers: { postmark: transports.postmark({ key: process.env.POSTMARK_TOKEN, baseUrl: 'https://api.postmarkapp.com', trackOpens: true, trackLinks: 'HtmlOnly' }) } }) ``` -------------------------------- ### Resend Transport Configuration Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/transports.md Defines the configuration schema and example setup for the Resend transport. ```typescript { key: string // Resend API key baseUrl: string // API base URL (e.g., https://api.resend.com) tags?: Array<{ // Email tags name: string value?: string }> } ``` ```typescript export default defineConfig({ default: 'resend', mailers: { resend: transports.resend({ key: process.env.RESEND_API_KEY, baseUrl: 'https://api.resend.com' }) } }) ``` -------------------------------- ### Define Global Template Variables Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Configuration schema and example for providing shared data to all email templates. ```typescript globals?: Record ``` ```typescript export default defineConfig({ globals: { appName: 'My Application', appUrl: 'https://example.com', supportEmail: 'support@example.com', year: new Date().getFullYear() } }) ``` -------------------------------- ### Define Global Sender Address Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Configuration schema and example for setting the default sender address. ```typescript from?: { address: string name?: string } | string ``` ```typescript export default defineConfig({ from: { address: 'noreply@example.com', name: 'My App' } }) ``` -------------------------------- ### Define Default Mailer Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Configuration schema and example for setting the default mailer used when none is specified. ```typescript default?: string ``` ```typescript export default defineConfig({ default: 'smtp', mailers: { smtp: transports.smtp({ /* ... */ }), postmark: transports.postmark({ /* ... */ }) } }) ``` -------------------------------- ### Transport-specific original response structures Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_response.md Examples of the raw response structures returned by different mail transports. ```typescript { messageId: string envelope: Envelope accepted?: string[] rejected?: string[] response?: string } ``` ```typescript { messageId: string envelope: Envelope accepted?: string[] rejected?: string[] response?: string } ``` ```typescript { id: string from: string to?: string[] created_at?: string } ``` -------------------------------- ### Retrieve Mailer Instance Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_manager.md Use the use method to get a cached mailer instance by name, or the default if no argument is provided. ```typescript // Use default mailer const defaultMailer = mailManager.use() // Use specific mailer const resendMailer = mailManager.use('resend') ``` -------------------------------- ### Log Email Message IDs Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_response.md Example implementation for logging email metadata to a database using AdonisJS Lucid. ```typescript import Database from '@adonisjs/lucid/services/database' export default class EmailLogger { static async log(mail: BaseMail, response: MailResponse, type: 'sent' | 'queued' = 'sent') { await Database.table('email_logs').insert({ message_id: response.messageId, type: type, from: response.envelope.from, to: JSON.stringify(response.envelope.to), subject: mail.message.nodeMailerMessage.subject, created_at: new Date() }) } } ``` -------------------------------- ### Handle E_MAIL_TRANSPORT_ERROR Errors Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/errors.md Examples demonstrating how to catch transport errors and implement retry logic for failed email deliveries. ```typescript import { errors } from '@adonisjs/mail' try { const response = await mailer.send((message) => { message .to('user@example.com') .subject('Hello') .html('

Hello World

') }) console.log(`Email sent with ID: ${response.messageId}`) } catch (error) { if (error.code === 'E_MAIL_TRANSPORT_ERROR') { console.error('Failed to send email:', error.message) // Optionally queue for retry } } ``` ```typescript import { errors } from '@adonisjs/mail' import retry from 'async-retry' async function sendEmailWithRetry(mailer, messageCallback) { try { return await retry(async () => { return await mailer.send(messageCallback) }, { retries: 3, minTimeout: 1000, maxTimeout: 5000 }) } catch (error) { if (error.code === 'E_MAIL_TRANSPORT_ERROR') { // Log for manual review await EmailLog.create({ status: 'failed', error: error.message, retries: 3 }) throw error } } } ``` -------------------------------- ### Implement complete mailer usage Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mailer.md Demonstrates configuring an SMTP transport, initializing the mailer, sending emails, queueing, and event listening. ```typescript import { Mailer, Message } from '@adonisjs/mail' import { SMTPTransport } from '@adonisjs/mail/transports/smtp' import { emitter } from '@adonisjs/core/services/emitter' // Create transport const transport = new SMTPTransport({ host: 'smtp.example.com', port: 587, auth: { type: 'login', user: 'user@example.com', pass: 'password' } }) // Create mailer const mailer = new Mailer('default', transport, emitter, { from: { address: 'noreply@example.com', name: 'My App' }, globals: { appName: 'My App' } }) // Send email await mailer.send((message) => { message .to('customer@example.com', 'Customer Name') .subject('Order Confirmation') .htmlView('emails/order-confirmation', { orderId: 12345 }) }) // Queue email await mailer.sendLater((message) => { message .to('admin@example.com') .subject('Daily Report') .htmlView('emails/daily-report') }) // Listen to events emitter.on('mail:sent', ({ mailerName, message }) => { console.log(`Email sent by ${mailerName}:`, message.subject) }) // Cleanup await mailer.close() ``` -------------------------------- ### Initialize Mailer Instance Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mailer.md Create a new Mailer instance by providing a name, transport, emitter, and optional configuration. ```typescript new Mailer( name: string, transport: Transport, emitter: EmitterLike, config?: MailerConfig ) ``` ```typescript const transport = new SMTPTransport(smtpConfig) const mailer = new Mailer('default', transport, emitter, { from: { address: 'noreply@example.com', name: 'App' } }) ``` -------------------------------- ### prepare() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md An abstract method that must be implemented to configure the email message, such as setting recipients, content, and attachments. ```APIDOC ## prepare() ### Description Abstract method that must be implemented to configure the email message. It is called during the build phase. ### Signature `abstract prepare(): void | Promise` ``` -------------------------------- ### Project File Structure Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/README.md Overview of the source directory layout for the mail package. ```text src/ ├── message.ts # Message fluent API ├── mailer.ts # Mailer implementation ├── mail_manager.ts # MailManager ├── base_mail.ts # BaseMail abstract class ├── fake_mailer.ts # FakeMailer for testing ├── mail_response.ts # MailResponse class ├── define_config.ts # defineConfig helper ├── errors.ts # Custom exceptions ├── types.ts # Type definitions ├── transports/ │ ├── smtp.ts │ ├── ses.ts │ ├── mailgun.ts │ ├── resend.ts │ ├── postmark.ts │ ├── brevo.ts │ ├── sparkpost.ts │ └── cloudflare.ts ├── messengers/ │ └── memory_queue.ts └── plugins/ └── edge.ts ``` -------------------------------- ### use() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_manager.md Retrieves or creates a mailer instance by name. If no name is provided, the default mailer is returned. ```APIDOC ## use(mailerName?) ### Description Get or create a mailer instance by name. If the name is omitted, the default mailer is returned. ### Parameters - **mailerName** (string) - Optional - Mailer name; uses default if omitted ### Returns Mailer instance (cached for process lifetime) ### Throws RuntimeException if mailer not found or no default configured ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Define mail driver settings and credentials in the .env file. ```text MAIL_DRIVER=smtp MAIL_FROM_ADDRESS=noreply@example.com MAIL_FROM_NAME="My Application" MAIL_REPLY_TO=support@example.com APP_URL=https://example.com SMTP_HOST=smtp.example.com SMTP_PORT=587 SMTP_SECURE=true SMTP_USERNAME=user@example.com SMTP_PASSWORD=password POSTMARK_TOKEN=abc123xyz RESEND_API_KEY=re_xyz AWS_REGION=us-east-1 AWS_ACCESS_KEY_ID=AKIA... AWS_SECRET_ACCESS_KEY=secret ``` -------------------------------- ### Initialize Message instance Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Creates a new Message instance with an empty mail configuration. ```typescript new Message() ``` -------------------------------- ### buildWithContents() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Builds the mail and renders all associated templates. ```APIDOC ## buildWithContents() ### Description Build the mail and render HTML, text, and watch templates. This method is idempotent. ### Signature `async buildWithContents(): Promise` ``` -------------------------------- ### Import Mail Configuration Helpers Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Required imports for setting up the mail configuration. ```typescript import { defineConfig, transports } from '@adonisjs/mail' ``` -------------------------------- ### Initialize and Use Mailer Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/README.md Wrap a transport with a mailer to utilize the send or sendLater API. ```typescript const mailer = new Mailer('smtp', transport, emitter, config) await mailer.send(messageCallback) ``` -------------------------------- ### build() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Builds the mail message by setting properties like subject and recipients, and calling the prepare method. ```APIDOC ## build() ### Description Build the mail message. This method is idempotent and safe to call multiple times. ### Signature `async build(): Promise` ``` -------------------------------- ### Select Mail Transport at Runtime Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/transports.md Demonstrates how to switch between configured mail transports or use the default transport within a controller. ```typescript import { inject } from '@adonisjs/core' import { MailService } from '@adonisjs/mail' @inject() export default class EmailController { constructor(private mail: MailService) {} async sendViaResend() { await this.mail.use('resend').send((message) => { // ... }) } async sendViaPostmark() { await this.mail.use('postmark').send((message) => { // ... }) } async sendUsingDefault() { // Uses default transport from config await this.mail.send((message) => { // ... }) } } ``` -------------------------------- ### Build mail with contents Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Builds the mail and renders all associated templates. ```typescript async buildWithContents(): Promise ``` -------------------------------- ### Implement prepare method Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Override the prepare method to configure email recipients, subjects, and view templates. ```typescript abstract prepare(): void | Promise ``` ```typescript class InvoiceMail extends BaseMail { subject = 'Your Invoice' prepare() { this.message .to(this.invoice.customer.email) .htmlView('emails/invoice', { invoice: this.invoice, customer: this.invoice.customer }) } } ``` -------------------------------- ### Create a simple email class Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Defines a basic email class by extending BaseMail and implementing the prepare method to set recipients and views. ```typescript import { BaseMail } from '@adonisjs/mail' export default class WelcomeMail extends BaseMail { subject = 'Welcome to our platform!' constructor(private user: User) { super() } prepare() { this.message .to(this.user.email, this.user.fullName) .htmlView('emails/welcome', { user: this.user }) .textView('emails/welcome-text', { user: this.user }) } } ``` -------------------------------- ### Mail Environment Variables Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/quick-reference.md Common configuration variables for setting up mail drivers and authentication credentials. ```text MAIL_DRIVER=smtp MAIL_FROM_ADDRESS=noreply@example.com MAIL_FROM_NAME="My App" SMTP_HOST=smtp.example.com SMTP_PORT=587 SMTP_SECURE=true SMTP_USERNAME=user@example.com SMTP_PASSWORD=password RESEND_API_KEY=re_xyz... POSTMARK_TOKEN=abc123... MAILGUN_API_KEY=key-xyz... MAILGUN_DOMAIN=mg.example.com BREVO_API_KEY=xkeysib... ``` -------------------------------- ### Render Apple Watch from template Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Renders the Apple Watch content using a template file. ```typescript watchView(template: string, data?: any): this ``` -------------------------------- ### listHelp(value) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Adds a List-Help header. ```APIDOC ### listHelp(value: ListHeader | ListHeader[] | ListHeader[][]): this Add `List-Help` header. #### Parameters - **value** (ListHeader | ListHeader[] | ListHeader[][]) - Required - The header value. ``` -------------------------------- ### Define Postmark configuration and response types Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/types.md Configuration and response structures for the Postmark mail driver. ```typescript type PostmarkConfig = PostmarkRuntimeConfig & { key: string baseUrl: string } type PostmarkRuntimeConfig = { messageStream?: string tag?: string trackOpens?: boolean trackLinks?: 'None' | 'HtmlAndText' | 'HtmlOnly' | 'TextOnly' metadata?: Record } type PostmarkSentMessageInfo = { messageId: string envelope: ResponseEnvelope MessageID?: string SubmittedAt?: string ErrorCode: number Message: string To?: string } ``` -------------------------------- ### Build mail message Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Use build to initialize the message configuration before sending. ```typescript async build(): Promise ``` ```typescript const mail = new WelcomeMail(user) await mail.build() console.log(mail.message.nodeMailerMessage.subject) ``` -------------------------------- ### icalEventFromFile(file, options?) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Attach a calendar event loaded from file. ```APIDOC ### icalEventFromFile(file, options?) Attach a calendar event loaded from file. **Signature:** `icalEventFromFile(file: string | URL, options?: CalendarEventOptions): this` **Returns:** this ``` -------------------------------- ### Select Mailer at Runtime Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Use the MailService to switch between mailers or handle delivery failures programmatically. ```typescript import { inject } from '@adonisjs/core' import { MailService } from '@adonisjs/mail' @inject() export default class EmailService { constructor(private mail: MailService) {} // Use specific mailer async sendCritical(mailCallback) { return await this.mail.use('postmark').send(mailCallback) } // Use default mailer async sendNotification(mailCallback) { return await this.mail.send(mailCallback) } // Fallback to queue if primary fails async sendWithFallback(mailCallback) { try { return await this.mail.send(mailCallback) } catch (error) { await this.mail.sendLater(mailCallback) } } } ``` -------------------------------- ### Initialize MailManager Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_manager.md Instantiate the MailManager with a configuration object defining the default mailer and available transport factories. ```typescript const config = { default: 'smtp', mailers: { smtp: () => new SMTPTransport(smtpConfig), resend: () => new ResendTransport(resendConfig) }, from: { address: 'noreply@example.com', name: 'App' } } const mailManager = new MailManager(emitter, config) ``` -------------------------------- ### Instantiate and Access Mail Errors Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/errors.md Demonstrates creating a mail error instance and accessing its properties. ```typescript import { errors } from '@adonisjs/mail' const error = new errors.E_MAIL_TRANSPORT_ERROR('SMTP connection failed') console.log(error.message) // 'SMTP connection failed' console.log(error.code) // 'E_MAIL_TRANSPORT_ERROR' console.log(error.status) // 500 ``` -------------------------------- ### Render plain text from template Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Renders the email plain text body using a template file. ```typescript textView(template: string, data?: any): this ``` -------------------------------- ### Define Brevo configuration and response types Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/types.md Configuration and response structures for the Brevo mail driver. ```typescript type BrevoConfig = BrevoRuntimeConfig & { key: string baseUrl: string } type BrevoRuntimeConfig = { scheduledAt?: Date tags?: string[] } type BrevoSentMessageInfo = { messageId: string envelope: ResponseEnvelope } ``` -------------------------------- ### from(address, name?) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Sets the sender email and name for the message. ```APIDOC ## from(address: string, name?: string) ### Description Sets the sender email and name. Returns the instance for method chaining. ### Example ```typescript message.from('noreply@example.com', 'My App'); ``` ``` -------------------------------- ### send() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Sends the mail using the provided mailer instance. ```APIDOC ## send() ### Description Send the mail using the provided mailer. ### Parameters - **mailer** (MailerContract) - Required - Mailer instance - **config** (unknown) - Optional - Transport-specific options ### Signature `async send>(mailer: T, config?: Parameters[1]): Promise>>` ``` -------------------------------- ### htmlView(template: string, data?: any) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Render HTML content from a template. ```APIDOC ## htmlView(template: string, data?: any) ### Description Render HTML content from a template. ### Parameters - **template** (string) - Required - Template path - **data** (object) - Optional - Data to pass to template ### Example ```typescript message.htmlView('emails/welcome', { name: 'John' }) ``` ``` -------------------------------- ### preparedHeader(key, value) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Defines a prepared header with a raw, unencoded value. ```APIDOC ### preparedHeader(key: string, value: string): this Define a prepared header (raw, unencoded value). #### Parameters - **key** (string) - Required - The header name. - **value** (string) - Required - The raw header value. ``` -------------------------------- ### Define SparkPost configuration and response types Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/types.md Configuration and response structures for the SparkPost mail driver. ```typescript type SparkPostConfig = SparkPostRuntimeConfig & { baseUrl: string key: string } type SparkPostRuntimeConfig = { startTime?: Date initialOpen?: boolean openTracking?: boolean clickTracking?: boolean transactional?: boolean sandbox?: boolean skipSuppression?: boolean ipPool?: string } type SparkPostSentMessageInfo = { id: string messageId: string envelope: ResponseEnvelope total_rejected_recipients: number total_accepted_recipients: number } ``` -------------------------------- ### Send emails using direct mailer calls Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Instantiate a mail class directly and use the mailer instance to send or queue the email. ```typescript const user = await User.find(1) const mail = new WelcomeMail(user) // Send const response = await mail.send(mailer) console.log(`Email sent with ID: ${response.messageId}`) // Or queue await mail.sendLater(mailer) ``` -------------------------------- ### Configure Mailers for Environments Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/README.md Define mailer transports using the defineConfig helper. Use environment variables for production keys and driver selection. ```typescript export default defineConfig({ default: 'smtp', mailers: { smtp: transports.smtp({ host: 'localhost', port: 1025, // Mailhog auth: { type: 'login', user: '', pass: '' } }) } }) ``` ```typescript export default defineConfig({ default: 'postmark', mailers: { postmark: transports.postmark({ key: process.env.POSTMARK_TOKEN, trackOpens: true }) } }) ``` ```typescript export default defineConfig({ default: process.env.MAIL_DRIVER, mailers: { postmark: transports.postmark({ /* ... */ }), ses: transports.ses({ /* ... */ }), resend: transports.resend({ /* ... */ }) } }) ``` -------------------------------- ### MailerContract.sendCompiled Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Sends a pre-compiled mail instance immediately. ```APIDOC ## sendCompiled(mail, config?) ### Description Sends a pre-compiled mail instance immediately and returns a promise that resolves to a MailResponse. ### Parameters - **mail** (any) - Required - The compiled mail instance. - **config** (any) - Optional - Configuration options for the mailer. ``` -------------------------------- ### attachData(content, options) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Attaches raw data as a buffer or stream as an attachment. ```APIDOC ## attachData(content, options) ### Description Attach raw data (Buffer or Stream) as an attachment. ### Signature `attachData(content: Readable | Buffer, options: AttachmentOptions & { filename: string }): this` ### Parameters - **content** (Readable | Buffer) - Required - The raw data to attach. - **options** (Object) - Required - Configuration options including a required filename. ### Example ```typescript const buffer = Buffer.from('content') message.attachData(buffer, { filename: 'data.txt' }) ``` ``` -------------------------------- ### Render HTML from template Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Renders the email HTML body using a template file and optional data. ```typescript htmlView(template: string, data?: any): this ``` ```typescript message.htmlView('emails/welcome', { name: 'John' }) ``` -------------------------------- ### Attach calendar event from file Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Loads and attaches a calendar event from a local file path or URL object. ```typescript icalEventFromFile(file: string | URL, options?: CalendarEventOptions): this ``` -------------------------------- ### Add attachments to email Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Uses the attach method within the prepare function to include files from the local filesystem. ```typescript import { BaseMail } from '@adonisjs/mail' import { join } from 'node:path' import { cwd } from 'node:process' export default class InvoiceMail extends BaseMail { subject = 'Your Invoice' constructor(private invoice: Invoice) { super() } prepare() { const invoicePath = join(cwd(), 'storage', `invoice-${this.invoice.id}.pdf`) this.message .to(this.invoice.customer.email) .htmlView('emails/invoice', { invoice: this.invoice }) .attach(invoicePath, { filename: `invoice-${this.invoice.id}.pdf` }) } } ``` -------------------------------- ### Define Cloudflare configuration and response types Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/types.md Configuration and response structures for the Cloudflare mail driver. ```typescript type CloudflareConfig = CloudflareRuntimeConfig & { key: string baseUrl: string accountId: string } type CloudflareRuntimeConfig = {} type CloudflareSentMessageInfo = { messageId: string envelope: ResponseEnvelope success: boolean result?: { delivered?: string[] permanent_bounces?: string[] queued?: string[] } } ``` -------------------------------- ### Perform asynchronous data loading Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Uses an async prepare method to fetch related database records before sending the email. ```typescript import { BaseMail } from '@adonisjs/mail' export default class OrderMail extends BaseMail { subject = 'Order Confirmation' constructor(private order: Order) { super() } async prepare() { // Load related data const items = await this.order.related('items').query() const customer = await this.order.related('customer').first() this.message .to(customer.email) .subject(`Order #${this.order.id} Confirmation`) .htmlView('emails/order-confirmation', { order: this.order, items, customer }) } } ``` -------------------------------- ### addListHeader(key, value) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Defines a List header. ```APIDOC ### addListHeader(key: string, value: ListHeader | ListHeader[] | ListHeader[][]): this Define a List header. #### Parameters - **key** (string) - Required - The header name. - **value** (ListHeader | ListHeader[] | ListHeader[][]) - Required - The list header value. ``` -------------------------------- ### Configure Mailers Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/README.md Define mailer transports and default settings in the configuration file. ```typescript import { defineConfig, transports } from '@adonisjs/mail' export default defineConfig({ default: 'smtp', from: { address: process.env.MAIL_FROM_ADDRESS || 'noreply@example.com', name: 'My App' }, mailers: { smtp: transports.smtp({ host: process.env.SMTP_HOST, port: process.env.SMTP_PORT, secure: true, auth: { type: 'login', user: process.env.SMTP_USERNAME, pass: process.env.SMTP_PASSWORD } }) } }) ``` -------------------------------- ### Attach files from disk Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Use attach() to add files to a message using a file path or URL. ```typescript message.attach('/path/to/file.pdf') message.attach(new URL('file:///path/to/file.pdf')) message.attach('/path/to/file.pdf', { filename: 'custom-name.pdf' }) ``` -------------------------------- ### transports.brevo Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Configures the Brevo transport. ```APIDOC ## transports.brevo(options) ### Description Configures the Brevo transport. ### Parameters - **key** (string) - Required - API key - **baseUrl** (string) - Required - API base URL - **scheduledAt** (Date) - Optional - Schedule time - **tags** (string[]) - Optional - Tags ``` -------------------------------- ### sendLater() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mailer.md Queues an email asynchronously using the configured messenger. ```APIDOC ## sendLater(callbackOrMail, config?) ### Description Queue an email asynchronously using the configured messenger. ### Parameters - **callbackOrMail** (MessageComposeCallback | BaseMail) - Required - Callback or mail class instance - **config** (unknown) - Optional - Transport-specific send options ### Returns Promise ``` -------------------------------- ### Instantiate MailResponse Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_response.md Create a new instance of MailResponse with a message ID, envelope, and transport-specific data. ```typescript const response = new MailResponse( 'message-id-123', { from: 'sender@example.com', to: ['recipient@example.com'] }, { /* smtp response */ } ) ``` -------------------------------- ### Define Resend configuration and response types Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/types.md Configuration and response structures for the Resend mail driver. ```typescript type ResendConfig = ResendRuntimeConfig & { key: string baseUrl: string } type ResendRuntimeConfig = { tags?: { name: string value?: string }[] } type ResendSentMessageInfo = { id: string messageId: string envelope: ResponseEnvelope } ``` -------------------------------- ### icalEvent(contents, options?) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Attach a calendar event defined by a callback or string. ```APIDOC ### icalEvent(contents, options?) Attach a calendar event defined by a callback or string. **Signature:** `icalEvent(contents: ((calendar: ICalCalendar) => void) | string, options?: CalendarEventOptions): this` **Returns:** this ``` -------------------------------- ### icalEventFromUrl(url, options?) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Attach a calendar event loaded from URL. ```APIDOC ### icalEventFromUrl(url, options?) Attach a calendar event loaded from URL. **Signature:** `icalEventFromUrl(url: string, options?: CalendarEventOptions): this` **Returns:** this ``` -------------------------------- ### Configure Mail Drivers and Settings Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/configuration.md Defines the mail configuration object using the defineConfig helper, including default settings, sender details, and multiple mailer transports. ```typescript import { defineConfig, transports } from '@adonisjs/mail' const mailConfig = defineConfig({ default: process.env.MAIL_DRIVER || 'smtp', from: { address: process.env.MAIL_FROM_ADDRESS || 'noreply@example.com', name: process.env.MAIL_FROM_NAME || 'My App' }, replyTo: { address: process.env.MAIL_REPLY_TO || 'support@example.com' }, globals: { appName: 'My Application', appUrl: process.env.APP_URL || 'http://localhost:3333', supportEmail: 'support@example.com', unsubscribeUrl: `${process.env.APP_URL}/unsubscribe` }, mailers: { smtp: transports.smtp({ host: process.env.SMTP_HOST || 'localhost', port: process.env.SMTP_PORT ? parseInt(process.env.SMTP_PORT) : 587, secure: process.env.SMTP_SECURE === 'true', auth: { type: 'login', user: process.env.SMTP_USERNAME || '', pass: process.env.SMTP_PASSWORD || '' } }), postmark: transports.postmark({ key: process.env.POSTMARK_TOKEN || '', baseUrl: 'https://api.postmarkapp.com', trackOpens: true }), resend: transports.resend({ key: process.env.RESEND_API_KEY || '', baseUrl: 'https://api.resend.com' }), ses: transports.ses({ region: process.env.AWS_REGION || 'us-east-1', credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID || '', secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || '' } }), mailgun: transports.mailgun({ key: process.env.MAILGUN_API_KEY || '', domain: process.env.MAILGUN_DOMAIN || '', baseUrl: 'https://api.mailgun.net' }) } }) export default mailConfig ``` -------------------------------- ### subject(message: string) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Define the email subject. ```APIDOC ## subject(message: string) ### Description Define the email subject. ### Signature `subject(message: string): this` ### Example ```typescript message.subject('Welcome to our app!') ``` ``` -------------------------------- ### Configure Messenger Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mailer.md Set the messenger instance used for asynchronous email delivery. ```typescript setMessenger(messenger: MailerMessenger): this ``` ```typescript import { Bull } from '@adonisjs/mail' const bullMessenger = new Bull() mailer.setMessenger(bullMessenger) ``` -------------------------------- ### Send email with attachments Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/quick-reference.md Attach files to an email using the attach method with optional filename configuration. ```typescript await mailer.send((message) => { message .to('user@example.com') .subject('Invoice') .htmlView('emails/invoice', { invoice }) .attach('/path/to/invoice.pdf') .attach('/path/to/terms.pdf', { filename: 'terms.pdf' }) }) ``` -------------------------------- ### attach(file, options) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Attaches a file from the local disk to the email message. ```APIDOC ## attach(file, options) ### Description Attach a file from disk to the email message. ### Signature `attach(file: string | URL, options?: AttachmentOptions): this` ### Parameters - **file** (string | URL) - Required - The path to the file on disk. - **options** (AttachmentOptions) - Optional - Configuration options for the attachment. ### Example ```typescript message.attach('/path/to/file.pdf') message.attach(new URL('file:///path/to/file.pdf')) message.attach('/path/to/file.pdf', { filename: 'custom-name.pdf' }) ``` ``` -------------------------------- ### send() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_manager.md Sends an email using the default mailer. ```APIDOC ## send(callbackOrMail, config?) ### Description Send email using the default mailer. ### Parameters - **callbackOrMail** (MessageComposeCallback | BaseMail) - Required - Callback or mail class - **config** (unknown) - Optional - Transport-specific options ### Returns Promise> ``` -------------------------------- ### sendLater() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_manager.md Queues an email for later delivery using the default mailer. ```APIDOC ## sendLater(callbackOrMail, config?) ### Description Queue email using the default mailer. ### Parameters - **callbackOrMail** (MessageComposeCallback | BaseMail) - Required - Callback or mail class - **config** (unknown) - Optional - Transport-specific options ### Returns Promise ``` -------------------------------- ### Send Email with Attachment Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/README.md Attaches a file to an email using the fluent message API. ```typescript await mailer.send((message) => { message .to('user@example.com') .subject('Invoice') .htmlView('emails/invoice', { invoice }) .attach('/path/to/invoice.pdf') }) ``` -------------------------------- ### Postmark Transport Usage Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/transports.md Demonstrates sending an email with metadata and message stream options using Postmark. ```typescript await mailer.use('postmark').send((message) => { message .to('user@example.com') .subject('Notification') .html('

Important update

') }, { messageStream: 'transactional', tag: 'notification', metadata: { userId: '12345' } }) ``` -------------------------------- ### sendLaterCompiled() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mailer.md Queues a pre-compiled email. ```APIDOC ## sendLaterCompiled(mail, sendConfig?) ### Description Queue a pre-compiled email. ### Parameters - **mail** (object) - Required - Compiled message and view templates - **sendConfig** (unknown) - Optional - Transport-specific send options ### Returns Promise ### Events Emits `mail:queueing` and `mail:queued` events ``` -------------------------------- ### Set sender with from() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Sets the sender email and name. ```typescript from(address: string, name?: string): this ``` ```typescript message.from('noreply@example.com', 'My App') ``` -------------------------------- ### Build Messages with Fluent API Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/README.md Construct email messages using the fluent API where each method returns the instance for chaining. ```typescript message .to('user@example.com', 'User Name') .subject('Hello') .htmlView('emails/greeting') .attach('/path/to/file.pdf') .header('X-Custom', 'value') ``` -------------------------------- ### setMessenger() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mailer.md Configures the messenger for async email sending. ```APIDOC ## setMessenger(messenger) ### Description Configure the messenger for async email sending. ### Parameters - **messenger** (MailerMessenger) - Required - Messenger instance ### Returns this (for chaining) ``` -------------------------------- ### Send mail Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/base_mail.md Sends the configured mail instance using a provided mailer. ```typescript async send>( mailer: T, config?: Parameters[1] ): Promise>> ``` ```typescript const mail = new OrderMail(order) const response = await mail.send(mailer) console.log(response.messageId) ``` -------------------------------- ### Define Mailgun configuration and response types Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/types.md Configuration and response structures for the Mailgun mail driver. ```typescript type MailgunConfig = MailgunRuntimeConfig & { baseUrl: string key: string domain: string } type MailgunRuntimeConfig = { oDkim?: boolean oTags?: string[] oDeliverytime?: Date oTestMode?: boolean oTracking?: boolean oTrackingClick?: boolean oTrackingOpens?: boolean headers?: Record variables?: Record } type MailgunSentMessageInfo = { id: string messageId: string envelope: ResponseEnvelope } ``` -------------------------------- ### Validate Mail Configuration Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/errors.md Ensures mail configuration is present during application startup. ```typescript // During app startup, validate mail config if (!config.mailers) { throw new errors.E_INVALID_CONFIG('No mailers configured') } ``` -------------------------------- ### computeContents() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Renders configured templates to compute email contents. ```APIDOC ## computeContents() ### Description Render configured templates to compute email contents. ### Signature `async computeContents(sharedState?: Record): Promise` ### Parameters - **sharedState** (object) - Optional - Shared state for template rendering ### Example ```typescript await message.computeContents({ appName: 'My App' }) ``` ``` -------------------------------- ### fake() Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_manager.md Enables fake mode for testing purposes, causing subsequent calls to use() to return a FakeMailer. ```APIDOC ## fake() ### Description Enable fake mode for testing. Subsequent calls to use() return a FakeMailer. ### Returns FakeMailer instance ``` -------------------------------- ### Send Email Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_manager.md Send an email immediately using the default mailer via a callback or mail class. ```typescript await mailManager.send((message) => { message.to('user@example.com') message.subject('Welcome!') }) ``` -------------------------------- ### Set Apple Watch content Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Sets the HTML content specifically for Apple Watch. ```typescript watch(content: string): this ``` -------------------------------- ### Queue Email for Async Sending Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/README.md Use sendLater to queue an email for asynchronous delivery. ```typescript // Queue for async sending await this.mail.sendLater((message) => { message .to('user@example.com') .subject('Notification') .html('

This sends asynchronously

') }) ``` -------------------------------- ### priority(priority: 'low' | 'normal' | 'high') Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Set email priority. ```APIDOC ### priority(priority: 'low' | 'normal' | 'high') Set email priority. **Signature:** `priority(priority: 'low' | 'normal' | 'high'): this` **Returns:** this ``` -------------------------------- ### html(content: string) Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Set the email HTML content directly. ```APIDOC ## html(content: string) ### Description Set the email HTML content directly. ### Signature `html(content: string): this` ### Example ```typescript message.html('

Welcome!

') ``` ``` -------------------------------- ### MailerTemplateEngine Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/types.md Interface for template engines used to render email bodies. ```APIDOC ## MailerTemplateEngine ### Description Interface for template engines (e.g., Edge.js) to render email templates. ### Methods - **render(templatePath, sharedState, data)**: Renders a template to a string. ``` -------------------------------- ### Restore Normal Behavior Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_manager.md Exit fake mode to return the mail manager to its standard operational state. ```typescript mailManager.fake() // ... test something mailManager.restore() ``` -------------------------------- ### Check for email headers Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/message.md Use hasHeader() to verify if a header exists, with an optional check for a specific value. ```typescript message.hasHeader('X-Custom-Header') message.hasHeader('X-Custom-Header', 'value') ``` -------------------------------- ### Utilize the Message API Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/quick-reference.md Methods for configuring email recipients, content, attachments, headers, and performing assertions during tests. ```typescript const message = new Message() // Recipients message.to('user@example.com', 'Name') message.cc('cc@example.com') message.bcc('bcc@example.com') message.from('sender@example.com', 'Sender Name') message.replyTo('reply@example.com') // Content message.subject('Subject') message.html('

HTML content

') message.text('Plain text') message.watch('Apple Watch HTML') message.htmlView('emails/template', { data: 'value' }) message.textView('emails/template-text', { data: 'value' }) // Attachments message.attach('/path/to/file.pdf') message.attachData(buffer, { filename: 'data.txt' }) message.embed('/path/to/image.png', 'image-cid') message.embedData(buffer, 'image-cid') // Headers message.header('X-Custom', 'value') message.preparedHeader('X-Prepared', 'raw value') // List headers message.listHelp('https://example.com/help') message.listUnsubscribe('https://example.com/unsubscribe') message.listUnsubscribe('https://example.com/unsubscribe', { oneClick: true }) message.listSubscribe('https://example.com/subscribe') // Calendar message.icalEvent((calendar) => { /* ... */ }) message.icalEventFromFile('/path/to/event.ics') message.icalEventFromUrl('https://example.com/event.ics') // Metadata message.messageId('custom-id') message.inReplyTo('message-id-123') message.references(['msg-1', 'msg-2']) message.priority('high') // 'low' | 'normal' | 'high' message.encoding('utf-8') // Assertions (for testing) message.assertTo('user@example.com') message.assertFrom('sender@example.com') message.assertSubject('Welcome!') message.assertHtmlIncludes('keyword') message.assertTextIncludes(/pattern/) message.assertAttachment('/path/to/file.pdf') message.assertHeader('X-Custom', 'value') // Checks message.hasTo('user@example.com') message.hasFrom('sender@example.com') message.hasSubject('Welcome!') message.hasAttachment('/path/to/file.pdf') message.hasHeader('X-Custom') // Serialization message.toObject() // { message: NodeMailerMessage, views: MessageBodyTemplates } ``` -------------------------------- ### Queue Email Source: https://github.com/adonisjs/mail/blob/10.x/_autodocs/mail_manager.md Queue an email for later delivery using the default mailer. ```typescript await mailManager.sendLater((message) => { message.to('user@example.com') message.subject('Notification') }) ```