Sending an email with attachments programmatically on Android

For newer devices you will encounter FileUriExposedException. Here is how to avoid it in Kotlin.

val file = File(Environment.getExternalStorageDirectory(), "this")
val authority = context.packageName + ".provider"
val uri = FileProvider.getUriForFile(context, authority, file)
val emailIntent = createEmailIntent(uri)
startActivity(Intent.createChooser(emailIntent, "Send email..."))

private fun createEmailIntent(attachmentUri: Uri): Intent {
    val emailIntent = Intent(Intent.ACTION_SEND)
    emailIntent.type = "vnd.android.cursor.dir/email"
    val to = arrayOf("[email protected]")
    emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
    emailIntent.putExtra(Intent.EXTRA_STREAM, attachmentUri)
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject")
    return emailIntent
}

Official documentation with Kotlin snippets is here: https://developer.android.com/guide/components/intents-common#ComposeEmail

I think your problem is that you are not using the correct file path.

The following works for me:

Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"[email protected]"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
emailIntent.putExtra(Intent.EXTRA_TEXT, "body text");
File root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "temp/attachement.xml";
File file = new File(root, pathToMyAttachedFile);
if (!file.exists() || !file.canRead()) {
    return;
}
Uri uri = Uri.fromFile(file);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));

EDIT: Requesting access to storage just to share a file private to your app is probably not a good idea. Fortunately, after a little configuration, it's very easy to share a file from your app private storage. See this guide: https://developer.android.com/training/secure-file-sharing/setup-sharing

If you share a file that is on external storage, you also need to give the user permission via a manifest file like below

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>