Mamoudou Kane
Mamoudou Kane

Reputation: 227

How to send an email from the user to the admin on flutter?

I am working on a flutter app and I need to implement a feature. I want to create a button and everytime the user presses it, if some conditions are respected, I automatically receive an email with informations of the user like his mail address. For example, the user hits enter his email address, hits the button, and then I, as an admin, receive an email with the email the user just wrote. How to implement this functionnality to my flutter app?

Upvotes: 1

Views: 1112

Answers (1)

Mithson
Mithson

Reputation: 1782

You can use available plugins to use mail services in flutter there are many such as url_launcher, http, and mailer. I prefer to use mailer for mail services its easy to use just follow these steps :

Add the following line to the pubspec.yaml file in your flutter application:

dependencies:
  mailer: 

then run below command in your console or cmd:

flutter pub upgrade --major-versions

now you need to import the plugin wherever you want to use this mailer plugin as:

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

Here I am creating a Gmail server for sending emails. It is easy to use and quick to implement.

main() async {
  String username = //Your Email;
  String password = //Your Email's password;

  final smtpServer = gmail(username, password); 
  // Creating the Gmail server

  // Create our email message.
  final message = Message()
    ..from = Address(username)
    ..recipients.add('[email protected]') //recipent email
    ..ccRecipients.addAll(['[email protected]', '[email protected]']) //cc Recipents emails
    ..bccRecipients.add(Address('[email protected]')) //bcc Recipents emails
    ..subject = 'Testing Dart Mailer plugin :: connectionEstablished :: ${DateTime.now()}' //subject of the email
    ..text = 'This is the plain text.\nThis is line 2 of the text part.' //body of the email

  try {
    final sendReport = await send(message, smtpServer);
    print('Message sent: ' + sendReport.toString()); //print if the email is sent
  } on MailerException catch (e) {
    print('Message not sent. \n'+ e.toString()); //print if the email is not sent
    // e.toString() will show why the email is not sending
  }
} 

Now you can use this code inside the InkWell() or GestureDetector() as:

body: yourWidget(
child: GestureDetector( 
      onTap: () { 
         // fire the mailer code here and you are good to go
      },
)

Upvotes: 1

Related Questions