Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
HomeF.A.Q.
Community
Writing Recipes
Login
Sending an email with attachments
Contributed by Marco Dinacci 2011-05-03 03:07:43 (updated 2012-11-28 08:56:05)
In Published Edition? Yes
0
Votes
Problem

You want to send an e-mail with attachments.

Solution

We're going to create an Intent, add extended data to specify the file we want to include and start a new activity to allow the user to send the e-mail.

Discussion

The easiest way to send an e-mail is to create an Intent of type ACTION_SEND.

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_SUBJECT, "Test single attachment");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient_address});
intent.putExtra(Intent.EXTRA_TEXT, "Mail with an attachment");

To attach a single file, we add some extended data to our intent:

intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/path/to/file")));
intent.setType("text/plain");

The MIME type can always be set as text/plain but you may want to be more specific so applications parsing your message will work properly. For instance if you're including a JPEG image you should write image/jpeg.

To send an e-mail with multiple attachment the procedure is slightly different:

Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Test multiple attachments");
intent.putExtra(Intent.EXTRA_TEXT, "Mail with multiple attachments");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient_address});
                                
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(Uri.fromFile(new File("/path/to/first/file")));
uris.add(Uri.fromFile(new File("/path/to/second/file")));

intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); 

First, we need to use Intent.ACTION_SEND_MULTIPLE, which is available since Android 1.6. Second, we need to create an ArrayList with the URIs of the files we want to attach to the mail and call putParcelableArrayListExtra.

If sending different type of files you may want to use multipart/mixed as MIME type.

Finally, in both cases, you can start a new Activity with the following code:

startActivity(Intent.createChooser(intent, "Send mail"));

Intent.createChooser is optional but will allow the user to select his favourite application to send the e-mail.

Code Repository Subdirectory The code example is in the "EmailWithAttachments" subdirectory of our GitHub repo, and can be viewed at https://github.com/androidcook/Android-Cookbook-Examples/tree/master/EmailWithAttachments You can also download the complete collection of examples at https://github.com/androidcook/Android-Cookbook-Examples/.
Comments (0)
Leave a comment
Edit History (4)
There are no (moderator-approved) comments on this recipe yet.