Search code examples
javaandroidemailemail-attachmentsgenymotion

Android Studio, Genymotion - sending email with txt file attachment: display in gmail, but doesn't send


Java, Android Studio, Genymotion.

Dear colleagues,

i'm sending email (Intent) with txt attach from android application. Txt file was created by application earlier. In genymotion in gmail client this attachment (file around 1 Kb) is displaying, but real mail is coming without attachment.

Code snippets:

    // file creating 
    ...
        final String FILENAME = "file";
    ...

    try {
            // отрываем поток для записи
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(openFileOutput(FILENAME, MODE_PRIVATE)));

            // writing any data

            bw.write ("\n");
...
            Log.d(LOG_TAG, "file is created");


            bw.close();
}

// sending email with intent 

    public void sendEmailwithMailClient (){

        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
// sending email

        emailIntent.setType("plain/text"); 
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"example@rambler.ru"}); 
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.app_name)); 
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hello!");


        File file = new File(getFilesDir(), FILENAME);

 //       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"));


    }

Do i correctly define Uri for attachment via getFilesDir() and FILENAME? Why email is loosing attachment during sending? It's issue of Genymotion or in reality i'm not attaching anything to mail and attach displaying in Genymotion is just a fake?

Thank you in advance!


Solution

  • You cannot attach a file from the your apps private storage. You need to save it to external storage and then attach.

    File file = new File(getFilesDir(), FILENAME);
    

    is creating your file in /data/data/package_name/files directory. Which is not accessible form the other apps. If you still want to share the file from the apps private storage you need to create your ContentProvider.