mailto: link for Flutter for Web
Asked Answered
S

2

14

The url_launcher package (https://pub.dev/packages/url_launcher) doesn't seem to work for Flutter for Web. The following code prints "test url1" but nothing happens afterwards.

How can I implement mailto: like functionality in Flutter for Web which causes the default email app to open with a prepopulated 'to:' email address?

FlatButton(
  onPressed: _mailto, //() => {},
  padding: EdgeInsets.all(3.0),
  child: _contactBtn(viewportConstraints),
)


  _mailto() async {
    const url = 'mailto:[email protected]?subject=Product Inquiry&body=';
    print("test url1");
    if (await canLaunch(url)) {
      print("test url2");
      await launch(url);
    } else {
      print("test url3");
      throw 'Could not launch $url';
    }
  }
Sall answered 5/11, 2019 at 5:24 Comment(1)
Full helper class that solves this: https://mcmap.net/q/830461/-flutter-send-email-with-url_launcher-uriWhey
E
14

After experimenting a little I found a way to make url_launcher work with web.

Don't use canLaunch(url). Instead, just use launch(url), but wrap it in try-catch block. This way you should be safe and the email link will work. For catch you can just copy the email to clipboard and notify the user about that with a snackbar or smth. Probably not the best solution, but a good one, till we get something better.

Here is the sample code, so that you see what I mean:

void _launchMailClient(String targetEmail) async {
  String mailUrl = 'mailto:$targetEmail';
  try {
    await launchUrlString(mailUrl);
  } catch (e) {
    await Clipboard.setData(ClipboardData(text: targetEmail));
  }
}
Eccles answered 18/1, 2020 at 21:53 Comment(2)
use await Clipboard.setData(ClipboardData(text: "$kEmail"));Tantamount
launch() is now deprecated you can use launchUrlString('mailto:$kEmail') instead.Krystenkrystin
P
2
import 'package:mailto/mailto.dart';

// For Flutter applications, you'll most likely want to use
// the url_launcher package.
import 'package:url_launcher/url_launcher.dart';

// ...somewhere in your Flutter app...
launchMailto() async {
    final mailtoLink = Mailto(
        to: ['[email protected]'],
        cc: ['[email protected]', '[email protected]'],
        subject: 'mailto example subject',
        body: 'mailto example body',
    );
    // Convert the Mailto instance into a string.
    // Use either Dart's string interpolation
    // or the toString() method.
    await launch('$mailtoLink');
}
Presbytery answered 16/6, 2021 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.