Sending email
suggest changeSending email is a core requirement for user verification, password resets, order receipts, and system alerts. In Dart, email delivery is typically achieved in one of two ways:
- SMTP Delivery via
package:mailer: Communicates directly with an SMTP server (such as Gmail, AWS SES SMTP, or custom mail servers). - Transactional REST APIs (
package:http): Dispatches emails via cloud delivery services (such as Resend, SendGrid, Mailgun, or Postmark) over HTTPS.
SMTP Email with package:mailer
The standard, feature-rich SMTP library for Dart is mailer.
Add mailer to your pubspec.yaml:
dependencies:
mailer: ^7.2.0
1. Sending Plaintext and HTML Emails
import 'dart:io';
import 'package:mailer/mailer.dart';
import 'package:mailer/smtp_server.dart';
Future<void> sendWelcomeEmail({
required String recipientEmail,
required String recipientName,
}) async {
// 1. Configure SMTP Server credentials (read from environment variables)
final username = Platform.environment['SMTP_USERNAME'] ?? 'user@example.com';
final password = Platform.environment['SMTP_PASSWORD'] ?? 'secret-app-password';
// Custom SMTP server configuration
final smtpServer = SmtpServer(
'smtp.mailerserver.com',
port: 587,
ssl: false,
username: username,
password: password,
allowInsecure: false,
);
// Or use built-in helpers for popular providers:
// final smtpServer = gmail(username, password);
// 2. Build the email message
final message = Message()
..from = Address(username, 'Acme Support')
..recipients.add(Address(recipientEmail, recipientName))
..subject = 'Welcome to Acme Services!'
..text = 'Hello $recipientName,\n\nThank you for signing up for Acme Services.'
..html = '''
<h1>Welcome, $recipientName!</h1>
<p>Thank you for signing up for <strong>Acme Services</strong>.</p>
<p><a href="https://example.com/activate">Click here to activate your account</a></p>
''';
// 3. Send the message
try {
final sendReport = await send(message, smtpServer);
print('Email sent successfully: $sendReport');
} on MailerException catch (e) {
print('Email delivery failed:');
for (final p in e.problems) {
print('Problem: ${p.code}: ${p.msg}');
}
}
}
Sending Attachments
package:mailer supports attaching binary files (such as PDFs, invoices, and images) via FileAttachment:
import 'dart:io';
import 'package:mailer/mailer.dart';
import 'package:mailer/smtp_server.dart';
Future<void> sendInvoiceWithAttachment(SmtpServer server, String customerEmail, File pdfInvoice) async {
final message = Message()
..from = const Address('billing@acme.com', 'Acme Billing')
..recipients.add(customerEmail)
..subject = 'Your Invoice for Order #1042'
..text = 'Please find your attached invoice in PDF format.'
..attachments = [
FileAttachment(pdfInvoice)
..location = Location.attachment
..cid = '<invoice@acme.com>'
..fileName = 'Invoice_1042.pdf',
];
await send(message, server);
print('Invoice email sent with PDF attachment.');
}
Transactional Email via Cloud REST API (e.g. Resend / SendGrid)
In cloud environments and serverless containers, opening persistent raw SMTP TCP sockets (port 25, 465, or 587) can be blocked by firewalls or cloud hosting providers. Sending emails via HTTPS REST APIs is faster, more reliable, and does not require SMTP connection handshakes:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<void> sendEmailViaRestApi({
required String to,
required String subject,
required String htmlContent,
}) async {
final apiKey = Platform.environment['RESEND_API_KEY'];
if (apiKey == null) throw StateError('Missing RESEND_API_KEY environment variable');
final url = Uri.parse('https://api.resend.com/emails');
final response = await http.post(
url,
headers: {
'Authorization': 'Bearer $apiKey',
'Content-Type': 'application/json',
},
body: jsonEncode({
'from': 'onboarding@resend.dev',
'to': [to],
'subject': subject,
'html': htmlContent,
}),
);
if (response.statusCode == 200 || response.statusCode == 201) {
print('Email dispatched via REST API: ${response.body}');
} else {
throw HttpException('Failed to send email (${response.statusCode}): ${response.body}');
}
}
Best Practices
- Never hardcode SMTP credentials: Store SMTP passwords and API tokens in environment variables or cloud secret stores.
- Use dedicated App Passwords: When sending via Gmail or Google Workspace, always generate an App Password with two-factor authentication instead of using your primary account password.
- Always provide both
textandhtml: Some email clients (and screen readers) only display plaintext; providing a clean plaintext fallback improves deliverability and accessibility. - Dispatch in background isolates or job queues: Sending email over SMTP can take several seconds due to network handshakes; never block incoming HTTP request loops on email delivery.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents