Using Android Intent.ACTION_SEND for sending email

[Solution for API LEVEL >=15]

I’ve finally succeded in sending email WITH attachments to ONLY email clients.
I write it here because it took me a lot of time and it may be usefull to others.

The problem is:

  • Intent.ACTION_SENDTO takes Data URI (so you can specify “mailto:”
    schema) BUT it does not accept Intent:EXTRA_STREAM.

  • Intent.ACTION_SEND accepts Intent:EXTRA_STREAM (so you can add
    attachment) BUT it takes only Type (not Data URI so you cannot
    specify “mailto:” schema).

So Intent.ACTION_SEND lets the user choose from several Activities, even if you setType(“message/rfc822”), because that App/Activities can manage all file types (tipically GDrive/Dropbox Apps) and so even email message files.

The solution is in the setSelector method.
With this method you can use Intent.ACTION_SENDTO to select the Activity, but then send the Intent.ACTION_SEND Intent.

Here my solution code (the attachment came from a FileProvider, but it could be any file):

{
    Intent emailSelectorIntent = new Intent(Intent.ACTION_SENDTO);
    emailSelectorIntent.setData(Uri.parse("mailto:"));

    final Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    emailIntent.setSelector( emailSelectorIntent );

    Uri attachment = FileProvider.getUriForFile(this, "my_fileprovider", myFile);
    emailIntent.putExtra(Intent.EXTRA_STREAM, attachment);

    if( emailIntent.resolveActivity(getPackageManager()) != null )
        startActivity(emailIntent);
}

Leave a Comment