Open In App

Mail and SMS in Flutter

Improve
Improve
Like Article
Like
Save
Share
Report

The world works in text. From advertisements to conversations, text is everywhere. The most popular modes of official textual communication are Mails followed by SMS. Companies use these modes to communicate not only with their employees but also with their customers. This had led app developers to include mailing and SMS services in their apps. Flutter uses special plugins, in order to bring these features live and working into mobile apps.

Adding dependencies in Flutter:

In Flutter, everything is a widget and in the same way, Flutter also uses a lot of plugins or dependencies in order to make the app work faster and easier. In this case, the “url_launcher” plugin can be used to launch the mail or SMS in a mobile application.

The steps for adding the plugin to the Flutter app are as follows:

  • Open “pubspec.yaml” file from the project folder.

pubspec.yaml file

  • In the pubspec.yaml file, type “url_launcher:” under dependencies.

After adding, the code looks like this:

Dart




dependencies:
 flutter:
   sdk: flutter
 url_launcher:


  • Now click “Pub Get” button at the top of the application (Android Studio).
  • The “Process finished with exit code 0“ in the console shows that the dependency is been added successfully.
  • Now import the plugin or package by adding the “import ‘package:url_launcher/url_launcher.dart’;” code to the top of the “main.dart” file.

Sending a Mail in Flutter:

Now, let’s create a function that can be called whenever the user clicks a button that’s linked to a particular Mail ID, to which the user can send a mail.

Dart




_sendingMails() async {
  var url = Uri.parse("mailto:feedback@geeksforgeeks.org");
  if (await canLaunchUrl(url)) {
    await launchUrl(url);
  } else {
    throw 'Could not launch $url';
  }
}


  1. The function is named here as “_sendingMails” and the function is declared as “async”, so that it returns a promise.
  2. The “url” variable is assigned with the required Mail ID, as a string. The syntax “mailto:” instructs the app to open the default mailing app of the mobile phone and also fill the “To” section with the Mail ID mentioned in the ‘url’ variable. It is declared as a “const” so that the variable is not changed at any circumstance.
  3. If there is a possibility to launch the URL, only then the URL is launched by calling the launch() function with URL variable as an attribute.
  4. Else, it will throw/print a text with the url value, as an error message.

Sending an SMS in Flutter:

Now, let’s create a function that can be called whenever the user clicks a button that’s linked to a phone number, to which the user can send an SMS.

Dart




_sendingSMS() async {
  var url = Uri.parse("sms:966738292");
  if (await canLaunchUrl(url)) {
    await launchUrl(url);
  } else {
    throw 'Could not launch $url';
  }
}


  1. The function is named here as “_sendingSMS” and the function is declared as “async”, so that it returns a promise.
  2. The “url” variable is assigned with the required phone number, as a string. The syntax “sms:” instructs the app to open the default messaging app of the mobile phone and also fill the “To” section with the phone number mentioned in the ‘url’ variable. It is declared as a “const”, so that the variable is not changed at any circumstance.
  3. If there is a possibility to launch the URL, only then the url is launched by calling the “launch()” function with url variable as an attribute.
  4. Else, it will throw/print a text with the url value, as an error message.

Calling the functions:

The above functions can be called whenever needed in code, by calling the name of the functions as such. The examples are as follows:

Dart




ElevatedButton(
   onPressed: _sendingMails,
  style: ButtonStyle(
    padding:
        MaterialStateProperty.all(const EdgeInsets.all(5.0)),
    textStyle: MaterialStateProperty.all(
      const TextStyle(color: Colors.black),
    ),
  ),
  child: const Text('Here'),
), // ElevatedButton
 
// DEPRECATED
// RaisedButton(
//   onPressed: _sendingMails,
//   child: Text('Here'),
//   textColor: Colors.black,
//   padding: const EdgeInsets.all(5.0),
// ),
 
ElevatedButton(
  onPressed: _sendingSMS,
  style: ButtonStyle(
    padding:
        MaterialStateProperty.all(const EdgeInsets.all(5.0)),
    textStyle: MaterialStateProperty.all(
      const TextStyle(color: Colors.black),
    ),
  ),
  child: const Text('Here'),
), // ElevatedButton
// DEPRECATED
// RaisedButton(
//   onPressed: _sendingSMS,
//   textColor: Colors.black,
//   padding: const EdgeInsets.all(5.0),
//   child: Text('Here'),
// ), child: const Text('Here'),


  1. This creates two raised buttons having the text “Here” and “Here” on it, respectively.
  2. For the onPressed attribute, we are calling _sendingMails and _sendingSMS respectively so that, when the first button is pressed the default mail app opens with the Mail ID filled in the “To” section and when the second button is pressed the default messaging app is opened with phone number filled in the “To” section.

Complete Source Code:

Dart




import 'package:flutter/material.dart';
// import 'package:flutter/cupertino.dart'; Unused Dependency
import 'package:url_launcher/url_launcher.dart';
 
// app build process is triggered here
void main() => runApp(const MyApp());
 
_sendingMails() async {
  var url = Uri.parse("mailto:feedback@geeksforgeeks.org");
  if (await canLaunchUrl(url)) {
    await launchUrl(url);
  } else {
    throw 'Could not launch $url';
  }
}
 
_sendingSMS() async {
  var url = Uri.parse("sms:966738292");
  if (await canLaunchUrl(url)) {
    await launchUrl(url);
  } else {
    throw 'Could not launch $url';
  }
}
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Geeks for Geeks'),
          backgroundColor: Colors.green,
        ),
        body: SafeArea(
          child: Center(
            child: Column(
              children: [
                Container(
                  height: 200.0,
                ),
                const Text(
                  'Welcome to GFG!',
                  style: TextStyle(
                    fontSize: 35.0,
                    color: Colors.green,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Container(
                  height: 20.0,
                ),
                const Text(
                  'For any Queries, Mail us',
                  style: TextStyle(
                    fontSize: 18.0,
                    color: Colors.green,
                    //fontWeight: FontWeight.bold,
                  ),
                ),
                Container(
                  height: 10.0,
                ),
                ElevatedButton(
                  onPressed: _sendingMails,
                  style: ButtonStyle(
                    padding:
                        MaterialStateProperty.all(const EdgeInsets.all(5.0)),
                    textStyle: MaterialStateProperty.all(
                      const TextStyle(color: Colors.black),
                    ),
                  ),
                  child: const Text('Here'),
                ), // ElevatedButton
 
                // DEPRECATED
                // RaisedButton(
                //   onPressed: _sendingMails,
                //   child: Text('Here'),
                //   textColor: Colors.black,
                //   padding: const EdgeInsets.all(5.0),
                // ),
                Container(
                  height: 20.0,
                ),
                const Text(
                  'Or Send SMS',
                  style: TextStyle(
                    fontSize: 18.0,
                    color: Colors.green,
                    //fontWeight: FontWeight.bold,
                  ),
                ),
                Container(
                  height: 10.0,
                ),
                ElevatedButton(
                  onPressed: _sendingSMS,
                  style: ButtonStyle(
                    padding:
                        MaterialStateProperty.all(const EdgeInsets.all(5.0)),
                    textStyle: MaterialStateProperty.all(
                      const TextStyle(color: Colors.black),
                    ),
                  ),
                  child: const Text('Here'),
                ), // ElevatedButton
 
                // DEPRECATED
                // RaisedButton(
                //   onPressed: _sendingSMS,
                //   textColor: Colors.black,
                //   padding: const EdgeInsets.all(5.0),
                //   child: Text('Here'),
                // ), child: const Text('Here'),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


Output:



Last Updated : 13 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads