Mail Module

Complete email sending solution for Khadem with support for multiple mail drivers, professional templates, and comprehensive testing tools.

Multiple Drivers

SMTP, Mailgun, SES, Postmark, Log, Array

Rich Features

HTML, attachments, inline images, queuing

Testing Support

ArrayTransport with comprehensive assertions

Quick Start

Get started with sending emails in Khadem in just a few steps.
dart

import 'package:khadem/khadem.dart';

// Get MailManager from container
final mailManager = container.resolve<MailManager>();

// Send your first email
await mailManager
    .to('user@example.com')
    .subject('Welcome!')
    .text('Thank you for joining us.')
    .html('<h1>Welcome!</h1><p>Thank you for joining us.</p>')
    .send();

print('Email sent successfully!');

Key Features

Khadem's mail module provides everything you need for professional email communication.

๐Ÿ“ง Multiple Mail Drivers

  • SMTP - Production email with TLS/SSL
  • Mailgun - Cloud email API
  • Amazon SES - AWS Simple Email Service
  • Postmark - Transactional email
  • Log - Development logging
  • Array - Testing with assertions

โœจ Rich Email Features

  • HTML and plain text emails
  • File attachments (path or raw data)
  • Inline embedded images
  • CC, BCC, Reply-To
  • Custom headers and priority
  • Queue integration for async sending

๐ŸŽฏ Mailable Classes

  • Object-oriented email composition
  • Lifecycle hooks (beforeSend, afterSend, onError)
  • Queue support with delays
  • Reusable email templates

๐Ÿงช Testing Support

  • ArrayTransport for in-memory storage
  • wasSentTo(), wasSentWithSubject() assertions
  • Full access to sent messages
  • Test-friendly architecture

Installation & Setup

The mail module is included in Khadem. Just register the service provider.
dart

import 'package:khadem/khadem.dart';

void main() async {
  final app = await Khadem.init(
    environment: 'development',
    providers: [
      // ... other providers
      MailServiceProvider(), // Add mail service provider
    ],
  );

  await app.start();
}

Basic Usage Examples

Simple examples to get you started with sending emails.
dart

import 'package:khadem/khadem.dart';

final mailManager = container.resolve<MailManager>();

// Simple text email
await mailManager
    .to('user@example.com')
    .from('sender@example.com', 'My App')
    .subject('Hello World')
    .text('This is a plain text email.')
    .send();
dart

// HTML email with plain text fallback
await mailManager
    .to('user@example.com')
    .subject('Newsletter')
    .html('''
      <h1>Newsletter</h1>
      <p>Latest updates...</p>
      <a href="https://example.com">Read More</a>
    ''')
    .text('Newsletter - Latest updates... Read more at https://example.com')
    .send();
dart

// Attach file from path
await mailManager
    .to('user@example.com')
    .subject('Invoice')
    .text('Please find your invoice attached.')
    .attach('/path/to/invoice.pdf', name: 'invoice.pdf')
    .send();

// Attach raw data
final data = utf8.encode('Report data');
await mailManager
    .to('user@example.com')
    .subject('Report')
    .attachData(data, 'report.txt', mimeType: 'text/plain')
    .send();

// Embed inline image
await mailManager
    .to('user@example.com')
    .subject('Welcome')
    .html('<h1>Welcome!</h1><img src="cid:logo">')
    .embed('/path/to/logo.png', 'logo')
    .send();

Using Mailable Classes

Create reusable, object-oriented email templates with Mailable classes.
dart

import 'package:khadem/khadem.dart';

class WelcomeMail extends Mailable {
  final String userEmail;
  final String userName;

  WelcomeMail({required this.userEmail, required this.userName});

  @override
  Future<void> build(MailerInterface mailer) async {
    mailer
        .to(userEmail)
        .subject('Welcome to Our App!')
        .html(_buildHtmlContent())
        .text(_buildTextContent());
  }

  String _buildHtmlContent() {
    return '''
      <!DOCTYPE html>
      <html>
        <head>
          <style>
            body { font-family: Arial, sans-serif; }
            .header { background: #3b82f6; color: white; padding: 20px; }
            .content { padding: 20px; }
          </style>
        </head>
        <body>
          <div class="header">
            <h1>Welcome $userName!</h1>
          </div>
          <div class="content">
            <p>We're excited to have you on board.</p>
            <p>Get started by exploring our features.</p>
          </div>
        </body>
      </html>
    ''';
  }

  String _buildTextContent() {
    return '''
Welcome $userName!

We're excited to have you on board.
Get started by exploring our features.
    ''';
  }

  @override
  Future<void> beforeSend() async {
    print('Sending welcome email to $userEmail');
  }

  @override
  Future<void> afterSend() async {
    print('Welcome email sent successfully');
  }
}
dart

// Send a mailable
final welcome = WelcomeMail(
  userEmail: 'user@example.com',
  userName: 'John Doe',
);

await mailManager.sendMailable(welcome);

// Or queue it for async sending
await mailManager.queueMailable(welcome, delay: Duration(minutes: 5));

Mail Driver Comparison

Choose the right mail driver for your needs.
DriverBest ForSetupCostAnalytics
SMTPSelf-hosted mail serversComplexServer costsโŒ
MailgunHigh volume emailsSimple APIPay-per-emailโœ…
Amazon SESAWS ecosystemAWS setupVery lowโœ…
PostmarkTransactional emailsSimple APIPer-emailโœ…
LogDevelopmentNoneFreeโŒ
ArrayTestingNoneFreeโŒ

On this page