Trigger default email app to send email in Flutter

To use the old fashion mail-to functionality in Flutter that make the user’s phone open up Gmail or whatever is the default email application to start composing an email is actually pretty simple. Just like in ordinary JavaScript where you do something like this:

window.location.href = 'mailto:address@fileidea.com&subject=Hello there&body=This is my message';

You can do it in a similar way in Dart. In your Flutter project add the dependency in your pubspec.yaml file under dependencies:

url_launcher: ^6.0.9

Now if you have let’s say a ListView like this that shows items:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FileIdea Example',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'FileIdea example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class EmailThing {
  late String title;
  late String email;

  EmailThing(title, email) {
    this.title = title;
    this.email = email;
  }
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final stuff = List<EmailThing>.generate(10,
        (i) => new EmailThing("thing ${i + 1}", "somerandomdomain$i@info.com"));

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: ListView.builder(
          itemCount: stuff.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              onTap: () => {
                print(
                  "hello from fileidea: " + stuff[index].email,
                )
              },
              tileColor: Colors.green[200],
              title: Text('${stuff[index].title}'),
            );
          },
        ),
      ),
    );
  }
}

You would obviously have the EmailThing class inside a separate folder and not inside the main.dart. Anyways, we have now a list with generated items that is of the type EmailThing, this class has two fields, an email field and a field for the title. We can pass these field values into our email program.

flutter listview with items listing (each containing a email address and title)

You click on one of the List items but nothing will happen, expect some logging. This is where I will put the function to call the launch function, which will open up the email program. Add the launch function like this:

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FileIdea Example',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'FileIdea example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class EmailThing {
  late String title;
  late String email;

  EmailThing(title, email) {
    this.title = title;
    this.email = email;
  }
}

class _MyHomePageState extends State<MyHomePage> {
  String? encodeQueryParameters(Map<String, String> params) {
    return params.entries
        .map((e) =>
            '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
        .join('&');
  }

  @override
  Widget build(BuildContext context) {
    final stuff = List<EmailThing>.generate(10,
        (i) => new EmailThing("thing ${i + 1}", "somerandomdomain$i@info.com"));

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: ListView.builder(
          itemCount: stuff.length,
          itemBuilder: (BuildContext context, int index) {
            final Uri emailLaunchUri = Uri(
              scheme: 'mailto',
              path: stuff[index].email,
              query: encodeQueryParameters(
                  <String, String>{'subject': stuff[index].title}),
            );

            return ListTile(
              onTap: () => {launch(emailLaunchUri.toString())},
              tileColor: Colors.green[200],
              title: Text('${stuff[index].title}'),
            );
          },
        ),
      ),
    );
  }
}

So at the row 71-82 is where the important things happen. We will first encode our query parameters such as subject so we got the characters displayed correctly, then we will call on the launch function which will trigger the email program, in this case Gmail, to open up like this:

open email app from flutter image with address and title

You can add body also if you would want that so you already have a message written for you!

            final Uri emailLaunchUri = Uri(
              scheme: 'mailto',
              path: stuff[index].email,
              query: encodeQueryParameters(<String, String>{
                'subject': stuff[index].title,
                'body': "Hey, this is FileIdea, how are you?"
              }),
            );
open email app from flutter image where we have the text in the body

And there you have it!

0 0 votes
Article rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments