Android intent mail client
In Android, you can use the Intent
class to send an email using the default mail client. Here's an example:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822"); // MIME type for email
String[] recipients = {"[email protected]", "[email protected]"};
String subject = "Test Email";
String body = "This is a test email";
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, body);
try {
startActivity(Intent.createChooser(intent, "Send email"));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "No email client installed", Toast.LENGTH_SHORT).show();
}
This code creates an Intent
with the ACTION_SEND
action and sets the MIME type to message/rfc822
, which is the standard MIME type for email. It then sets the recipients, subject, and body of the email using the EXTRA_EMAIL
, EXTRA_SUBJECT
, and EXTRA_TEXT
extras.
Finally, it uses the createChooser
method to create a chooser dialog that allows the user to select which email client to use to send the email. If no email client is installed, it displays a toast message.
You can also use Intent.createChooser
with a specific email client, for example:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.setPackage("com.google.android.gm"); // Gmail client
String[] recipients = {"[email protected]", "[email protected]"};
String subject = "Test Email";
String body = "This is a test email";
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, body);
try {
startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "No email client installed", Toast.LENGTH_SHORT).show();
}
This code sets the package name of the email client to com.google.android.gm
, which is the package name of the Gmail client. This will open the Gmail client directly, without showing a chooser dialog.
Note that the Intent
class is used to send an email, but it's not guaranteed that the email will be sent successfully. The email client may not be able to send the email, or the user may not have an internet connection. You should handle these cases accordingly.