4

I am attempting to use the email intent in Android Studio 3.01. If I use ACTION_SENDTO, I get an error No apps can perform this action even though the stock Android email client and the Gmail email app are both installed. If I use ACTION_SEND in place of ACTION_SENDTO, a screen is shown displaying every app on the device.

My goal is to invoke the default email client directly, without going through an intervening screen. What am I doing wrong?

The code I'm using is:

public void sendEmail(View view) {

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.setType("text/plain");

    try {
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        finish();
        Log.i("Email sent!", "");
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MapsActivityCurrentPlace.this,
                "Email not installed.", Toast.LENGTH_SHORT).show();
    }
}

EDITED

Thanks to the answer, final working code looks like:

public void sendEmail(View view) {

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "Message...");

    try {
        startActivity(emailIntent);
        finish();
        Log.i("Email sent!", "");
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MapsActivityCurrentPlace.this,
                "Email not installed.", Toast.LENGTH_SHORT).show();
    }
}

}

Ryan M
  • 18,333
  • 31
  • 67
  • 74
hermitjimx
  • 61
  • 10

1 Answers1

7

First, ACTION_SENDTO does not take a MIME type. So, get rid of setType(). That solves two problems:

  1. You are artificially restricting to apps that would claim to support that MIME type

  2. setType() wipes out your setData() call (setType(type) is the same as setDataAndType(null, type))

Second, if your goal is to launch an email client directly, get rid of createChooser().

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks for your help. If I use `ACTION_SENDTO` the app crashes. If I remove `createChooser` the app crashes :( – hermitjimx Feb 17 '18 at 21:50
  • 1
    @hermitjimx: Use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this. Bear in mind that email clients might not appreciate a `mailto:` `Uri` that does not have an actual email address in it. – CommonsWare Feb 17 '18 at 21:54
  • Got it working. Agree with your point about the empty `"mailto:"` - seems like a fudge but can't think of any other way to let the user choose a recipient. For some reason I can't uptick your answer, but very many thanks for your help. – hermitjimx Feb 17 '18 at 22:10