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.

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

dependencies:
  flutter:
    sdk: flutter
  url_launcher: ^6.1.5

Now import the package to your script:

import 'package:url_launcher/url_launcher.dart';

String email = Uri.encodeComponent("[email protected]");
String subject = Uri.encodeComponent("Hello Flutter");
String body = Uri.encodeComponent("Hi! I'm Flutter Developer");
print(subject); //output: Hello%20Flutter
Uri mail = Uri.parse("mailto:$email?subject=$subject&body=$body");
if (await launchUrl(mail)) {
    //email app opened
}else{
    //email app is not opened
}

Replace the email address, subject, and body with your own configuration.

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

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> { 

  @override
  Widget build(BuildContext context) { 
    return  Scaffold(
          appBar: AppBar(
            title: Text("Open Mailer"),
            backgroundColor: Colors.redAccent,
          ),
          body: Container(
            padding: EdgeInsets.only(top:20, left:20, right:20),
            alignment: Alignment.topCenter,
            child: Column(
              children: [
                 ElevatedButton(
                  onPressed: ()async{
                      String email = Uri.encodeComponent("[email protected]");
                      String subject = Uri.encodeComponent("Hello Flutter");
                      String body = Uri.encodeComponent("Hi! I'm Flutter Developer");
                      print(subject); //output: Hello%20Flutter
                      Uri mail = Uri.parse("mailto:$email?subject=$subject&body=$body");
                      if (await launchUrl(mail)) {
                          //email app opened
                      }else{
                          //email app is not opened
                      }
                  }, 
                  child: Text("Mail Us Now")
                )
            ],)
          )
       );
  }
}

In this way, you can open the default email app with the receiver's email address, subject, and body in Flutter.

No any Comments on this Article


Please Wait...