'Unable to attach file to Email in Android 10

I am trying to attach pdf to Gmail using file provider. It is working on Android 6.0 but says 'Couldn't attach file'

fun startFileShareIntent(filePath: String, context: Context?) {
    try {
        val file = File(filePath)
        val uri = FileProvider.getUriForFile(context!!, "com.trust.inspakt.android.provider", file)

        val intent = ShareCompat.IntentBuilder.from(context as Activity)
            .setType("application/pdf")
            .setStream(uri)
            .setChooserTitle("Choose bar")
            .createChooserIntent()
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        context.startActivity(intent)

    } catch (e: Exception) {
        e.printStackTrace()
    }

}


Solution 1:[1]

I assume from your question that it is working on Android 7.0 and up?

In Android 6.0 there is no need for a file provider. Here is the Java code that I am using to attach a csv file to gmail. This works for me from Android 6.0 up to Android 11.

/* This is the filename or file URI, depending on what Android version you have 
and how you got the filename */
String fileInfo; 
final Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_EMAIL,"[email protected]");
emailIntent.putExtra(Intent.EXTRA_SUBJECT,"subject");
emailIntent.putExtra(Intent.EXTRA_TEXT,emailBody);
//add file to email according to build type
if (Build.VERSION.SDK_INT>=Q){
    Uri path = Uri.parse(fileInfo);
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    emailIntent.putExtra(Intent.EXTRA_STREAM, path);
}
else if (Build.VERSION.SDK_INT>M) {
    File test_result = new File(fileInfo);
    String authority = context.getApplicationContext().getPackageName() + ".provider";
    Uri path = FileProvider.getUriForFile(context.getApplicationContext(),authority,test_result);
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    emailIntent.putExtra(Intent.EXTRA_STREAM, path);
}
else {
    File test_result = new File(fileInfo);
    Uri path = Uri.fromFile(test_result);
    emailIntent.putExtra(Intent.EXTRA_STREAM, path);
}

//send email
context.startActivity(emailIntent);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Danielle