22 May 2024 Leave a comment Tech-Help
Sending an email directly from an Android application can enhance user experience by allowing users to contact support, share content, or send feedback without leaving the app. This guide will show you how to filter out non-email apps from the chooser dialog, ensuring only email-related apps are displayed.
Using Intent.ACTION_SENDTO for Email Intents
To ensure that only email apps appear in the chooser dialog, use Intent.ACTION_SENDTO
with the “mailto:” URI scheme. This method is effective across different Android versions and ensures a consistent experience for users.
Code Example
public void composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
This method sets up an intent that only email apps can handle. The resolveActivity
check ensures that there is an app available to handle the intent before attempting to start it.
Alternative Approaches
Here are some additional methods to achieve similar functionality:
- Custom Uri: Build a custom URI to include subject and body parameters.
Uri uri = Uri.parse("mailto:" + email) .buildUpon() .appendQueryParameter("subject", subject) .appendQueryParameter("body", body) .build(); Intent emailIntent = new Intent(Intent.ACTION_SENDTO, uri); startActivity(Intent.createChooser(emailIntent, chooserTitle));
- Support Library ShareCompat: Use the ShareCompat.IntentBuilder for more complex sharing needs.
ShareCompat.IntentBuilder.from(activity) .setType("message/rfc822") .addEmailTo(email) .setSubject(subject) .setText(body) .setChooserTitle(chooserTitle) .startChooser();
Practical Example
Consider the following practical example where we send an email with a subject and body text:
String[] addresses = {"[email protected]"};
String subject = "Feedback";
composeEmail(addresses, subject);
This code will open the email client with the specified recipient and subject pre-filled, allowing the user to add their message and send the email.
Enhancing Your Development Process with Repeato
Maintaining and testing email intents manually can be time-consuming. This is where Repeato, our no-code test automation tool, can significantly streamline your workflow. Repeato allows you to create, run, and maintain automated tests for your iOS and Android apps efficiently.
With Repeato, you can easily automate the testing of email intents, ensuring that they work correctly across different devices and configurations. This frees up your time to focus on developing new features and improving your app’s user experience.
For more information on how Repeato can help you with test automation, visit our documentation or contact us for a demo.