0

My program sends a .txt documment with an Intent, it works in any Android version but with Android 11 the file doesn't attach in Gmail but in other apps like Outlook it does, Once Gmail is opened it sends me a toast with the message "Coulnd't attach the file", Any Solution? (Note: I request the permissions to the user, but I think it is not necessary to attach this code)

The permissions in the Manifest:

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

And these are my classes to send the email and to generate the .txt:

String CARPETA_PRINCIPAL = "Folder/";
String CARPETA_DOCTXT = "Files";
String DIRECTORIO_TXT = CARPETA_PRINCIPAL + CARPETA_DOCTXT;


public void sendEmail() {
    String nombre_completo = exportTxt();
    if (!nombre_completo.equals("")){
        Intent email = new Intent(Intent.ACTION_SENDTO);
        email.setData(Uri.parse("mailto:"));
        email.putExtra(Intent.EXTRA_SUBJECT, "Exportation File");
        email.putExtra(Intent.EXTRA_TEXT, "Hello2");
        File file = new File(nombre_completo);
        email.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        startActivity(Intent.createChooser(email, "Send Email"));
    } else {
        Toast.makeText(this, "Something happen", Toast.LENGTH_LONG).show();
    }
}

public String exportTxt(){
    String fileName= "file.txt";
    File folder = new File(Environment.getExternalStorageDirectory(), DIRECTORIO_TXT);
    if (!folder.exists()) {
        folder.mkdir();
    }

    nombre_completo = Environment.getExternalStorageDirectory() + File.separator + DIRECTORIO_TXT + File.separator + fileName;

    File outputFile = new File(nombre_completo);
    if (outputFile.exists()) {
        outputFile.delete();
    }

    try {
        FileWriter fileWriter = new FileWriter(outputFile);
        BufferedWriter bw = new BufferedWriter(fileWriter);
        bw.write("Hello");
        bw.flush();
        bw.close();
    } catch (Exception e) {
        Log.i("Error: ",String.valueOf(e));
    }
    return nombre_completo;
}

The uri is something like this, I think it is correct:

/storage/emulated/0/Folder/Files/file.txt

  • 1
    One cannot use .uriFromFile() since Android 7/N. Use FileProvider to serve your file. – blackapps Jul 21 '21 at 17:46
  • 1
    there are already answers to this question https://stackoverflow.com/questions/66641751/couldnt-attach-file-send-email-android-11 – Alberto Sinigaglia Jul 21 '21 at 17:47
  • Does this answer your question? [couldn't attach file send email android 11](https://stackoverflow.com/questions/66641751/couldnt-attach-file-send-email-android-11) – Alberto Sinigaglia Jul 21 '21 at 17:47
  • You may have added a `StrictMode` hack to [get past a `FileUriExposedException`](https://stackoverflow.com/q/38200282/115145). Get rid of that hack and `Uri.forFile()`, then use `FileProvider` instead. – CommonsWare Jul 21 '21 at 17:48

0 Answers0