[Flutter tips] Easily send an email from your iOS and Android app (code included)



When you design a mobile application, at some point, you will always need to propose the user a way to contact your or your support team.

You can use different services or back-end, the most easy and fast way to achieve this functionality is to propose to the user to send you directly an email.

Here are the steps to send an email.


1. Add package url_launcher

In your yaml file:

dependencies:

  url_launcher: ^6.1.9



2. Use a correctly formatted link to send email

In your controller, format your address like that, providing:
- the recipient email address
- and optionally a subject and a body 
 

mailto:target@example.com?subject=Sujet&body=Contenu
 

3. Sample code


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

class EmailExample extends StatelessWidget {
  final String email = 'destinataire@example.com';
  final String subject = 'Mon Sujet Pré-rempli';
  final String body = 'Bonjour, voici un exemple de contenu pour votre e-mail.';

  Future sendEmail() async {
    final Uri emailUri = Uri(
      scheme: 'mailto',
      path: email,
      query: 'subject=${Uri.encodeComponent(subject)}&body=${Uri.encodeComponent(body)}',
    );

    if (await canLaunchUrl(emailUri)) {
      await launchUrl(emailUri);
    } else {
      print('Impossible d\'ouvrir l\'application de messagerie.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Exemple d\'envoi d\'e-mail')),
      body: Center(
        child: ElevatedButton(
          onPressed: sendEmail,
          child: Text('Envoyer un e-mail'),
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: EmailExample()));
}


4. Explanation of Parameters

  • mailto: Scheme used to open email applications.
  • path: The recipient's email address.
  • query: Additional parameters, such as:
    • subject: The email subject.
    • body: The email content.

5. Notes

  1. Pre-filling only:
    • The user must always confirm the email sending in their email application. This method does not allow emails to be sent directly without user intervention.
  2. Cross-platform compatibility:
    • Works on iOS, Android, and Web.
    • Ensure the simulator or device has a configured email application.
  3. Data encoding:
    • The subject and body parameters must be encoded using Uri.encodeComponent to avoid errors related to special characters.
  4. Alternative for automatic sending:
    • If you want to send emails directly from your application without user intervention, you will need to use a backend service or libraries like mailer with an SMTP server.

Comments

Popular posts from this blog

EMGU with Xamarin Forms guide [part 1]

Xamarin Forms essential: FFImageLoading, manage your images

[SocialCut] released! Make instagram grids, panorama and more