How to send yourself email notifications from a Dart server

Suragch
5 min readJul 22, 2021

A guide to using the mailer package

Photo by Brett Jordan

When an important event happens on your Dart server, it would be nice to get a notification. One way to do that is to send yourself an email. This article will cover how to do that using the mailer package.

You’ll create a simple Dart server where every time someone makes a POST request to the /contact endpoint, Mailer will send you an email containing the body of the POST.

You can find the full code at the bottom of the article.

What is SMTP?

The way Mailer works is by helping you connect to an SMTP server, but that begs the question, “What’s an SMTP server?”

SMTP stands for Simple Mail Transfer Protocol, and just like HTTP is a protocol (or set of rules) for transferring web traffic, SMTP is a protocol for transferring email. So an SMTP server is an email server. It’s used for sending email, but not receiving it. IMAP and POP3 are protocols for receiving email.

Creating the basic server

Before adding the Mailer package, first make a basic Dart server that accepts POST requests.

Start with a new Dart project:

dart create my_server

Replace bin/my_server.dart with the following code:

import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final server = await createServer();
print('Server started: ${server.address} port ${server.port}');
await _handleRequests(server);
}
Future<HttpServer> createServer() async {
final address = InternetAddress.loopbackIPv4;
const port = 4040;
return await HttpServer.bind(address, port);
}
Future<void> _handleRequests(HttpServer server) async {
await for (HttpRequest request in server) {
if (request.method == 'POST' &&
request.uri.path == '/contact') {
_handleContactPost(request);
} else {
_handleBadRequest(request);
}
}
}
void _handleBadRequest(HttpRequest request) {
request.response
..statusCode = HttpStatus.badRequest
..write('Bad request')
..close();
}

--

--