Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Sending an Email with Attachments

Author: Marco Dinacci -- Published? true -- FormatLanguage: W


You want to send an e-mail with attachments.


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.


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")));

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.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.


The source code for this project is in the Android Cookbook repository at http://github.com/IanDarwin/Android-Cookbook-Examples, in the subdirectory EmailWithAttachments.
No records found.