constantlyFlagged
constantlyFlagged

Reputation: 398

How to send text file via email as an attachment - Android?

I have looked at many codes online but all of them seem to run into a problem.

File is created and saved using the below function:

    private static String filename = "eulerY.txt" ;

    private void saveData() {

      

        FileOutputStream fos_FILE_eulerY = null;

        String message = "hello";
        try {
            fos_FILE_eulerY = openFileOutput(filename , MODE_PRIVATE);
            fos_FILE_eulerY.write(message.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos_FILE_eulerY != null) {
                try {
                    fos_FILE_eulerY.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        // export data
        sendEmail ();
    }

However, when running the below code to send the file, I keep running into the problem ClipData.Item.getUri And as suggested using all the answer from this link "https://stackoverflow.com/questions/48117511/exposed-beyond-app-through-clipdata-item-geturi", when opening Gmail, it says "unable to attach file"

    private void sendEmail (){
        File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
        Uri path = Uri.fromFile(filelocation);
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
       // set the type to 'email'
        emailIntent .setType("vnd.android.cursor.dir/email");
        String to[] = {"[email protected]"};
        emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
      // the attachment
        emailIntent .putExtra(Intent.EXTRA_STREAM, path);
      // the mail subject
        emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
        startActivity(Intent.createChooser(emailIntent , "Send email..."));
    }


I would appreciate it if there is any way to send this file.

Upvotes: 3

Views: 2831

Answers (1)

NRUSINGHA MOHARANA
NRUSINGHA MOHARANA

Reputation: 1559

If your targetSdkVersion >= 24, then we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.

Step-1: Add below code in AndroidManifest.xml file.

        <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

Step-2

Create a xml folder inside res folder. And create a file namely file_paths.xml because look at above code inside <meta-data>.

file_paths.xml

<paths>
    <external-path name="external_files" path="."/>
</paths>

Step-3 Now you could save file inside your package.private folder and you can share file uri saved inside this folder to other app, for example gmail app as an attachment. Now your method looks like:

    private void saveData() {
    String filename = "eulerY.txt" ;
    //FileOutputStream fos_FILE_eulerY = null;
    File externalFilesDirectory = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
    File textFile = new File(externalFilesDirectory,filename);
    String message = "hello";
    try {
        //fos_FILE_eulerY = openFileOutput(textFile.getAbsolutePath() , MODE_PRIVATE);
        //fos_FILE_eulerY.write(message.getBytes());
        FileWriter writer = new FileWriter(textFile);
        writer.append(message);
        writer.flush();
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e){
        e.getLocalizedMessage();
    }


    // export data
    sendEmail (textFile);
}

    private void sendEmail (File file){
    //File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
    //Uri path = Uri.fromFile(filelocation);
    //FileProvider.getUriForFile(it, "${it.packageName}.provider", file)
    Uri fileUri = FileProvider.getUriForFile(this,getPackageName()+".provider",file);
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    // set the type to 'email'
    emailIntent .setType("vnd.android.cursor.dir/email");
    String[] to = {"[email protected]"};
    emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
    // the attachment
    emailIntent .putExtra(Intent.EXTRA_STREAM, fileUri);
    // the mail subject
    emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
    startActivity(Intent.createChooser(emailIntent , "Send email..."));
}

Upvotes: 7

Related Questions