Select Page

These days, working with email is a habitual activity. One of the fundamental uses of email is to share photos or other files with friends, family, or colleagues.

” Please find the attached document… “

We would have written this line over a hundred times in our lifetime because, in this computer world, we used the above-mentioned sentence in multiple circumstances (applying for a job, status reports etc)

So now in this post, we are going to discuss how to attach a document to an E-mail.

For this, first we have to select a file, So this file selection happens by using any one of the following ways.

1. Selection from local storage(Using native intent)
2. Selection from Assets folder

1. Read file from Assets:

AssetManager through this class we can easily access any files lying inside the Assets directory of the android application.

AssetManager assetManager = getAssets();
InputStream in = assetManager.open("sample.pdf");

Using this AssetManager and Input stream we have the data as a stream and create a temporary file using this stream with the help of IOUtils.

public File stream2file(InputStream in) throws IOException
{
final File tempFile = File.createTempFile("sample1", ".pdf",
HomeActivity.this.getExternalCacheDir());
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
// for this you have to add the following dependency in your build.gradle
// compile 'org.apache.commons:commons-io:1.3.2'
IOUtils.copy(in, out);
return tempFile;
}

2. Read file from storage using Intent :

For this we simply use implicit intent and also for filtering the attachment file type, we can easily mention the type of data with the help of MIME TYPE field. Specifying the MIME type of your data helps the Android system find the best component for your intent.

private void browseDocuments()
{
String[] mimeTypes =
{"application/msword", "text/plain", "application/pdf", "application/zip"};
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
}
startActivityForResult(Intent.createChooser(intent, "ChooseFile"), 100);
}

Sending Email with attachment :

After getting the file from any one of the above-specified ways, we can attach those files to the email using the following snippet. For this, we have the recipient details and also the mail details like Subject, Text and so on.

String mailID = "jaisonfdo@gmail.com";
String mailSubject = "Attachment Sample";

Now we have to check the network availability and also the email client application presence for this you can use the following piece of code.

public static boolean isNetworkAvailable(Context context)
{
if (checkInternetConnection) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
return true;
else {
if (showErrorMessage)
Toast.makeText(context, networkErrorMessage, Toast.LENGTH_SHORT).show();
return false;
}
} else
return true;
}

public static Boolean isAppAvailable(Context context, String appName)
{
PackageManager pm = context.getPackageManager();
boolean isInstalled;
try {
pm.getPackageInfo(appName,PackageManager.GET_ACTIVITIES);
isInstalled = true;
} catch (PackageManager.NameNotFoundException e) {
isInstalled = false;
}
return isInstalled;
}

Finally, we have to initiate the process by using the implicit intent.

public void sendMail(Context context, String mailID, String subject, File attachment, Uri uri)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_EMAIL, mailID);
// Need to grant this permission
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Attachment
intent.setType("vnd.android.cursor.dir/email");
if (attachment != null)
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(attachment));
else if (uri != null)
intent.putExtra(Intent.EXTRA_STREAM, uri);
if (!TextUtils.isEmpty(subject))
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (isNetworkAvailable(context)) {
if (isAppAvailable(context, "com.google.android.gm"))
intent.setPackage("com.google.android.gm");
startActivityForResult(intent, 101);
}
}

This concludes the post. You are now ready to start making your own Android Studio Project that consists of email attachment feature limited only by your imagination. That’s it. Happy coding ????

The source code is available on GitHub, use the below links to get the application.

View on GithubDownload .zip

Feel free to comment and share, keep watching this space get more updates on Android Stuff!

Elsewhere

Jaison Fernando

Android Developer at NFN Labs
Elsewhere