Reputation: 4950
What is the best way on Android to send an email with multiple attachments without having non-email apps in the chooser?
When sending emails, I used to do it like this:
final Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.setType("message/rfc822");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
...
Unfortunately, "message/rfc822" no longer works well for filtering out undesired apps from the chooser, such as Evernote, Drive, and various other apps.
I recently found this workaround that works for single attachments:
sendEmailIntent = new Intent(Intent.ACTION_SENDTO);
Uri data = Uri.parse("mailto:[email protected]&subject...");
sendEmailIntent.setData(data);
...
Unfortunately, this doesn't work for multiple attachments. I tried it, and it crashes Gmail. :S
Upvotes: 1
Views: 385
Reputation: 4950
I finally found a solution, albeit one that only works on Ice Cream Sandwich MR1 and above. The trick is to first build your intent using ACTION_SEND_MULTIPLE:
sendEmailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
sendEmailIntent.setType("message/rfc822");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
final ArrayList<Uri> uris = /* ... Your code to build the attachments. */
sendEmailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
To restrict it to email apps only, add this code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
sendEmailIntent.setType(null); // If we're using a selector, then clear the type to null. I don't know why this is needed, but it doesn't work without it.
final Intent restrictIntent = new Intent(Intent.ACTION_SENDTO);
Uri data = Uri.parse("mailto:[email protected]");
restrictIntent.setData(data);
sendEmailIntent.setSelector(restrictIntent);
}
When you fire this intent with startActivity(), you'll now only see email apps in the list, and if you select Gmail, the multiple attachments will be there.
I do this with a try/catch in case startActivity resolves to no activities, in which case I remove the selector, and it seems to work well.
Upvotes: 5