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 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.
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
Top comments (0)