How to Open Email App With Address, Subject and Body in Flutter

In this post, we are going to show you how to open the default email app along with receiver’s email address, subject, and body text in Flutter. This example will help you to make the “email us” button on your contact page, which will be very easy for users to email you.

Adding dependencies in Flutter

add url_launcher package to your project by adding the following lines in pubspec.yaml file.

  url_launcher: ^6.1.5 //latest   version
  • 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.

How to Open Email App with Address, Subject, and Body:

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.

 _sendingMails() async {
  var mailId="****@gmail.com";
  var subject="Hello Demo Subject";
  var message="Hiii .........";
  await launchUrl(Uri.parse("mailto:$mailId?subject=$subject&body=$message"));
}
Dart
  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.

How to Open SMS App with Number and Body:

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

_sendingSMS() async {
var number="122******7";
  var url = Uri.parse("sms:$number");
  if (await canLaunchUrl(url)) {
    await launchUrl(url);
  } else {

    throw 'Could not launch $url';
  }
}
Dart
  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.

Full code

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          brightness:Brightness.light,
            seedColor: Colors.green,
            primary: Colors.green,
          secondary: Colors.white,

        ),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Mail and SMS'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int selected=0;

  var number=TextEditingController();
  var mailId=TextEditingController();
  var message=TextEditingController();
  var subject=TextEditingController();
  @override
  Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
      backgroundColor: Theme.of(context).colorScheme.inversePrimary,
         title: Text(widget.title),
      ),
      body: Center(
        child: ListView(
          children: <Widget>[
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(2, (index) => Padding(
                padding: const EdgeInsets.all(8.0),
                child: RawMaterialButton(
                  onPressed: () {
                    setState(() {
                      selected=index;
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.all(20),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      color: selected==index?Theme.of(context).primaryColorLight:null,
                      border:Border.all(color: Theme.of(context).textTheme.bodyMedium!.color!)
                    ),
                    child: Text(index==0?"Mail":"SMS"),),
                ),
              ))
            ),
            selected==1?textFieldCustome(controller: number, hint: "Enter Number",type: TextInputType.number):Container(),
            selected==1?Container():textFieldCustome(controller: mailId, hint: "Mail Id",type: TextInputType.number),
            selected==1?Container():textFieldCustome(controller: subject, hint: "Subject",type: TextInputType.number),
            textFieldCustome(controller: message, hint: "Message",type: TextInputType.number),
            ElevatedButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStatePropertyAll(Theme.of(context).primaryColor)
                ),
                onPressed: (){
                  selected==0
                      ?launchUrl(Uri.parse("mailto:${mailId.text}?subject=${subject.text}&body=${message.text}"))
                      :launchUrl(Uri.parse("sms:+91${number.text}?body=${message.text}"));
                }, child: Text(selected==0?"Send Mail":"Send SMS",style: Theme.of(context).textTheme.bodyText1,))
          ],
        ),
      ),
     );
  }

  textFieldCustome({required TextEditingController controller,required String hint,TextInputType? type}){
    return     Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        controller: controller,
        keyboardType: type,
        decoration: InputDecoration(
          hintText: hint,
          border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(10),
              borderSide: BorderSide(color: Theme.of(context).cardColor)
          ),

        ),
      ),
    );
  }

}
Dart

Output