How to Send Emails in Flutter Using SMTP: A Simplest Guide
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'.
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 go to 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.
Now open your flutter project and run following command to install mailer library:
flutter pub add mailer
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);
}
}
Complete TODO in above code and your function is ready to send mail.
You can add additional attachments & html to mail by using
..attachments
&..html
Resources : Official Mailer Library
This article provides a step-by-step guide to adding email functionality in a Flutter app using the 'mailer' library. It covers creating a Gmail App Password, configuring the SMTP server, and sending an email with optional HTML content and attachments.
Subscribe to my newsletter
Read articles from Om Vastre directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by