Android open default mail client
To open the default mail client on Android, you can use the following approaches:
- Intent: You can use the
Intent
class to open the default mail client. Here's an example:Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setType("mailto:*"); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"}); intent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); intent.putExtra(Intent.EXTRA_TEXT, "Body");
try { startActivity(Intent.createChooser(intent, "Send email")); } catch (ActivityNotFoundException e) { // Handle the case where no email client is installed }
This code creates an `Intent` with the `ACTION_SENDTO` action, sets the `type` to `"mailto:*"` to indicate that it's an email intent, and adds the recipient, subject, and body as extras. The `startActivity` method is then used to launch the default mail client.
2. **Android's built-in `Email` intent**: You can use the `Email` intent, which is a built-in intent in Android. Here's an example:
```java
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Body");
try {
startActivity(Intent.createChooser(intent, "Send email"));
} catch (ActivityNotFoundException e) {
// Handle the case where no email client is installed
}
This code creates an Intent
with the ACTION_SEND
action, sets the type
to "message/rfc822"
to indicate that it's an email intent, and adds the recipient, subject, and body as extras. The startActivity
method is then used to launch the default mail client.
- Using a third-party library: You can also use a third-party library like
android-intent
orIntentBuilder
to simplify the process of creating and launching an intent.
Remember to handle the case where no email client is installed on the device, as the startActivity
method will throw an ActivityNotFoundException
in that case.