4

How can I open a device email to send an email on the new update of android? it's showing a list of applications with support text/message/html/plain with the following code?

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{context.getString("email_to")});
    intent.putExtra(Intent.EXTRA_SUBJECT, context.getString("email_subject"));
    context.startActivity(Intent.createChooser(intent, context.getString("email_body")));
Sagar
  • 5,273
  • 4
  • 37
  • 50

2 Answers2

12

This Intent will work For Email client with mailto Uri:

try {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"example.yahoo.com"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "App feedback");
    startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
    ToastUtil.showShortToast(getActivity(), "There are no email client installed on your device.");
}
ADM
  • 20,406
  • 11
  • 52
  • 83
  • do we really need to do a try-catch? it wouldn't crash the app would it? – Aba Jun 11 '18 at 02:47
  • 1
    It will crash the app if no Activity found which handles data `mailto:`. So always use try catch or use `resloveActivity()`. – ADM Jun 11 '18 at 14:54
5

I have found the following code to open the email app programmatically use the following code. I hope this may solve your problem.

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("mailto:"+"email_to"));
intent.putExtra(Intent.EXTRA_SUBJECT, "email_subject");
intent.putExtra(Intent.EXTRA_TEXT, "email_body");
startActivity(intent);
Sagar
  • 5,273
  • 4
  • 37
  • 50
  • I followed this code. But in my One Plus 3, email address doesn't get added in gmail sender field. – viper Apr 06 '20 at 12:55