How to send an email in Dart with mailer/smtp_server package

How to send an email in Dart with mailer/smtp_server package

ยท

4 min read

Meet me:

Hello everyone, my name is Emmanuel and I'm thrilled to be writing my first blog post. I'm currently learning Dart and Flutter, two powerful tools for building dynamic and engaging mobile apps. I have always been fascinated by technology and how it can be used to create amazing experiences for users. That's why I'm so excited about my journey with Dart and Flutter. Through this blog, I hope to share my experiences, challenges, and successes as I continue to grow and develop as a mobile app developer. Thank you for joining me on this journey, and I look forward to connecting with you all!

Now how do we actually send an email with dart?

To send an email in Dart using the mailer/smtp_server package, you need to follow a few simple steps. And in this simple tutorial, we'll be building a dart application that sends motivational quotes via email each time the program is run:

  1. Add the mailer package to dependencies in pubspec.yaml like this:

     dependencies:
       mailer: ^6.0.0
    

    or run 'dart pub add mailer' in your terminal. Both will work just fine.

     dart pub add mailer
    
  2. Import the required packages

     import 'package:mailer/mailer.dart';
     import 'package:mailer/smtp_server.dart';
     import './motivation.dart';
    
  3. Now you want to define the username and password properties because you'll need them as arguments to pass to the SMTP server.

     import 'package:mailer/mailer.dart';
     import 'package:mailer/smtp_server.dart';
     import './motivation.dart';
    
     void main(List<String> args) async {
       final mo = Motivation(); // Creating an instance of the Motivation class
       String username = 'anyemail@gmail.com';
       String password = 'password';
    
  4. Connect to the SMTP server using the SMTP server details:

     // Use the SmtpServer class to configure an SMTP server:
       // Supports major smtp servers like gmail, hotmail, yahoo, and sendgrid. 
       final smtpServer = hotmail(username, password);
    
  5. Create a new instance of the Mailer class and set the sender, recipients, subject, and body:

     // Create our message.
       final message = Message()
         ..from = Address(username, 'ManuelTheTechGuy')
         ..recipients.add('afrikareportersng@gmail.com')
         ..subject = 'Get Motivated! :: ๐Ÿ˜€ :: ${DateTime.now()}'
         ..text = '${mo.motivations['afternoon']}';
    

As you can see from the code, the email body(..text) is being rendered from another file which I'll show you in a bit. The file contains a class named 'Motivation', and it serves as a kind of blueprint on how data can be collected or transferred. This method is known as Data-Transfer-Model, and you'll use it a lot as you continue to practice and work with dart.

class Motivation {
  Map<String, List<Map<String, Object>>> motivations = {
    "morning": [
      {
        "text": '"Be happy"',
        "author": 'anon',
      },
      {
        "text": '"Eat Code Sleep"',
        "author": 'Steve Jobs',
      },
    ],
    "afternoon": [
      {
        "text": '"It\'s noon... rest a bit!"',
        "author": 'wolf_hunter',
      },
      {
        "text": '"Be happy"',
        "author": 'anon',
      },
    ],
    "evening": [
      {
        "text": '"Evening hour... go for a walk!"',
        "author": 'anon',
      },
      {
        "text": '"You\'re amazing... keep the momentum!"',
        "author": 'viperOS',
      },
    ]
  };
}

I'm guessing you noticed the nice syntax we used above when instantiating the Mailer class. It's called 'cascades', and it is used to chain together operations that would otherwise require separate statements, very easy to use. You can read more about it on the official dart website:

Finally, let's send our email by passing the message instance and SMTP server we set earlier as arguments to the send function that the mailer package provides for us like so:

try {
    final sendReport = await send(message, smtpServer);
    print('Message sent: ' + sendReport.toString());
  } on MailerException catch (e) {
    print('Message not sent.');
    for (var p in e.problems) {
      print('Problem: ${p.code}: ${p.msg}');
    }
  }
}

Here's the full source code of our app:

import 'package:mailer/mailer.dart';
import 'package:mailer/smtp_server.dart';
import './motivation.dart';

void main(List<String> args) async {
  final mo = Motivation();
  String username = 'anyemail@gmail.com';
  String password = 'password';

  // Use the SmtpServer class to configure an SMTP server:
  // Supports major smtp servers like gmail, hotmail, yahoo, and sendgrid. 
  final smtpServer = hotmail(username, password);

  // Create our message.
  final message = Message()
    ..from = Address(username, 'ManuelTheTechGuy')
    ..recipients.add('afrikareportersng@gmail.com')
    ..subject = 'Get Motivated! :: ๐Ÿ˜€ :: ${DateTime.now()}'
    ..text = '${mo.motivations['afternoon']}';

  try {
    final sendReport = await send(message, smtpServer);
    print('Message sent: ' + sendReport.toString());
  } on MailerException catch (e) {
    print('Message not sent.');
    for (var p in e.problems) {
      print('Problem: ${p.code}: ${p.msg}');
    }
  }
}

In this blog post, you learned how easy it was to send emails with dart, and you also saw how to use dart classes as blueprints to model your data. I'm sure you found this content very useful, please like, comment with your feedback, and share. Please don't forget to follow me on my socials where I post about my projects, and also useful programming materials and tips. In my next blog post, I'll be writing about how to work with collections in dart. Until then, happy coding!

ย