Send Email Programmatically in Flutter Using SMTP (Simplest Way)

devom04

Om Vastre

Posted on July 22, 2024

Send Email Programmatically in Flutter Using SMTP (Simplest Way)

So many times we need to add email sending functionality to our flutter app, for that SMTP is first solution that comes in mind. There are various ways to send email programmatically but I'm sharing the simplest I found. I used it to send OTP to email for verification in flutter.
We are going to use a library called 'mailer'.

  1. So first of all we need a Gmail and App Password to send SMTP mail from respective mail. To create app password:

    • Sign in with gmail account from which you want to send mail.
    • Then goto Manage my google account
    • Now you have to turn on 2 Step verification in order to create App Password
    • For that go to Security > How you sign in to Google > 2-Step Verification
    • Enter your password, then mobile no and turn it on.
    • Now search for 'App Password' in search bar, open it and create a new passkey of 16 character. Save it somewhere we require it further.
  2. Now open your flutter project and run following command to install mailer library: flutter pub add mailer

  3. Now add following function to your code to send mail:

import 'package:flutter/material.dart';
import 'package:mailer/mailer.dart';
import 'package:mailer/smtp_server/gmail.dart';

sendEmail(BuildContext context) async {
  // TODO : Enter details below
  String name = ''; // your name
  String username = ''; // mail
  String password = ''; // 16 character long app password
  String receiverMail = ''; // receiver's mail
  String sub = ''; // subject of mail
  String text = ''; // text in mail

  final smtpServer = gmail(username, password);
  // SmtpServer class to configure an SMTP server: final smtpServer = SmtpServer('smtp.domain.com');

  final message = Message()
    ..from = Address(username, name)
    ..recipients.add(receiverMail)
    ..subject = sub
    ..text = text
  ..html = "<h4>Your message</h4><p> Your message</p>"; // For Adding Html in email
  // ..attachments = [
  //   FileAttachment(File('image.png'))  //For Adding Attachments
  //     ..location = Location.inline
  //     ..cid = '<myimg@3.141>'
  // ];

  try {
    final sendReport = await send(message, smtpServer);
    print('Message sent: ' + sendReport.toString());
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text("Email Send Successfully")));
  } catch (e) {
    print('Message not sent.');
    print(e);
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Complete TODO in above code and your function is ready to send mail.

  2. You can add additional attachments & html to mail by using ..attachments & ..html

Resources : Official Mailer Library

💖 💪 🙅 🚩
devom04
Om Vastre

Posted on July 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related