You can use the `mailer` package in Dart to send and receive emails.

How to compose mail and download emails in Dart or Flutter

  • Table of contents

Dart is a great programming language from Google that is widely used in cross platform app development. In this post we'll show you how to send and receive emails within Dart code. This can be used in apps to send login emails or in tests to test user sign-up or notifications.

Install Dart

First thing we need to install Dart. On a mac we can use brew like so:

brew tap dart-lang/dart
brew install dart

Configure a project

Create a new directory and add a pubspec.yaml to describe the project and dependencies:

name: dart_email_testing
description: A simple command-line application.
version: 1.0.0

  sdk: '>=2.12.0 <3.0.0'

  test: ^1.24.4
  mailslurp: ^15.17.22

Create a simple test

Next we can write a simple test to demonstrate email sending. Let's call it test/email-test.dart.

Inside the test file import the io and test packages.

import 'dart:io';

import 'package:test/test.dart';

Setup email client

Next we can use the mailslurp package to configure email sending and receiving. It's free for personal use but requires an API Key.

import 'package:mailslurp/api.dart';

Then add a setup function:

void main() async {
  setUp(() {
    // will configure here

Next add configuration for MailSlurp:

// read api key from environment variable
var apiKey = Platform.environment["API_KEY"];
expect(apiKey != null, true);

// set api key on default client
defaultApiClient.addDefaultHeader('x-api-key', apiKey!);

Creating email addresses

Disposable email mailboxes are a common need during testing. We can create an inbox using MailSlurp like this:

var inboxController = InboxControllerApi(defaultApiClient);
var inbox = await inboxController.createInboxWithOptions(CreateInboxDto());
expect(inbox!.emailAddress.contains("@mailslurp"), true);

Send emails in dart

To send emails use the inbox controller with an inbox ID:

var confirmation = await inboxController.sendEmailAndConfirm(inbox!.id,
        to: [inbox.emailAddress],
        subject: "Test email",
        body: "<html>My message</html>",
        isHTML: true

Receive and read emails

To download emails we can use an instance of the WaitForControllerApi(defaultApiClient) to wait for an expected email in a given inbox:

var email = await waitForController.waitForLatestEmail(
    timeout: 60000,
    unreadOnly: true
expect(email!.subject, "Test email");

Next steps

Dart has many other email abilities. To find out more see the MailSlurp documentation.