Unable to attach files to Gmail from cache directory Android 12

399 Views Asked by At

I almost found many similar links - and none helped

  1. Gmail is not allowing me to get file from /storage/emulated/0/Android/data/myapppackage/cache/..pdf tried both manually using Gmail and programmatically
  2. Able to attach if the same file is downloaded to /storage/emulated/0/download/..pdf

CODE -

protected void sendEmail(Context ctx, String filePath){
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Uri uri = Uri.fromfile(new File(filePath)));
    emailIntent.setType("application/pdf");
    emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "PDF"));
    ctx.startActivity(emailIntent);
}

file_provder.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="cache" path="/" />
    <files-path name="files" path="/" />
</paths>

Tried the following link which almost seems like perfect but doesn't work for me - Attaching cache file to GMail through FileProvider and Intent not working

1

There are 1 best solutions below

0
On

This might help someone in the future, instead of getting uri directly from file path i just used file provider to get the uri which returns content://path

protected void sendEmail(Context ctx, String filePath){
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Uri uri = FileProvider.getUriForFile(ctx, ctx.getPackageName, (new File(filepath)));
    emailIntent.setType("application/pdf");
    emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "PDF"));
    ctx.startActivity(emailIntent);
}