[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
- 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.
- Cross-platform compatibility:
- Works on iOS, Android, and Web.
- Ensure the simulator or device has a configured email application.
- Data encoding:
- The
subject
andbody
parameters must be encoded usingUri.encodeComponent
to avoid errors related to special characters.
- The
- 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.
- If you want to send emails directly from your application without user intervention, you will need to use a backend service or libraries like
Comments
Post a Comment