MailSender is a static utility class for sending email via SMTP. It wraps the mailer package.
Import
import 'package:finch/finch_mail.dart';
Sending an Email
bool success = await MailSender.sendEmail(
from: '[email protected]',
fromName: 'My App',
host: env['MAIL_HOST'] ?? 'smtp.example.com',
port: int.tryParse(env['MAIL_PORT'] ?? '587') ?? 587,
username: env['MAIL_USER'] ?? '',
password: env['MAIL_PASS'] ?? '',
ssl: true,
allowInsecure: false,
to: ['[email protected]'],
subject: 'Welcome to My App',
html: '<h1>Hello!</h1><p>Your account is ready.</p>',
text: 'Hello! Your account is ready.',
);
if (!success) {
Console.e('Failed to send email');
}
MailSender.sendEmail Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
from |
String |
required | Sender email address |
fromName |
String |
'' |
Sender display name |
host |
String |
'localhost' |
SMTP server hostname |
port |
int |
1025 |
SMTP port (typically 465/587) |
username |
String? |
— | SMTP username |
password |
String? |
— | SMTP password |
ssl |
bool |
true |
Enable SSL/TLS |
allowInsecure |
bool |
true |
Allow insecure connection (no SSL) |
to |
List<String> |
required | Recipient addresses |
subject |
String |
'' |
Email subject |
html |
String |
'' |
HTML body |
text |
String |
'' |
Plain-text body |
Controller Example
class HomeController extends Controller {
Future<String> sendTestEmail() async {
var email = rq.get<String>('email', def: '');
if (email.isEmpty) return rq.renderError(400, message: 'Missing email');
var sent = await MailSender.sendEmail(
from: '[email protected]',
host: env['MAIL_HOST'] ?? 'localhost',
port: int.tryParse(env['MAIL_PORT'] ?? '1025') ?? 1025,
username: env['MAIL_USER'],
password: env['MAIL_PASS'],
ssl: false,
to: [email],
subject: 'Test',
html: '<p>This is a test email from Finch.</p>',
);
return rq.renderData(data: {'success': sent});
}
}
Development Setup
For local development, use MailHog or Mailpit as a local SMTP server:
# Docker
docker run -d -p 1025:1025 -p 8025:8025 axllent/mailpit
Then configure:
MAIL_HOST=localhost
MAIL_PORT=1025
Open http://localhost:8025 in your browser to see captured emails.