2

I want to share a file made and written using Service via email. I know I can't share a private file with email but how to use the content provider to do that. I read online that content Provider can help but I can't make it work. (I merged file creation code together with intent creation for simplicity)

Intent email = new Intent(Intent.ACTION_SEND);
    email.putExtra(Intent.EXTRA_EMAIL, new String[]{ "someone@gmail.com"});
    email.putExtra(Intent.EXTRA_SUBJECT, "Nothing");
    email.putExtra(Intent.EXTRA_TEXT, "Nothing");
    email.setType("message/rfc822");
    Uri uri = null;
    try {
        File file = new File(this.getExternalFilesDir(null), "samplefile.txt");
        uri = FileProvider.getUriForFile(this, "lcukerd.com.android.fileprovider", file);
        FileOutputStream osw = new FileOutputStream(file);
        osw.write("Say something".getBytes("UTF-8"));
        osw.close();

        Log.i("File Reading stuff", "success");

    } catch (Exception e)
    {
        Log.e(tag,"File creation error",e);
    }
    //Uri uri =  FileProvider.getUriForFile(this, "lcukerd.com.android.fileprovider", );
    //Uri uri = Uri.fromFile(getFileStreamPath("samplefile.txt"));
    Log.d(tag,uri.toString());
    email.putExtra(Intent.EXTRA_STREAM,uri);
    startActivityForResult(Intent.createChooser(email, "Choose an Email client :"),1);

I get option to choose app but then nothing happens. Gmail app does not open.

Gmail opens if I use Uri uri = Uri.fromFile(getFileStreamPath("samplefile.txt")); but then I get "permission denied for attachment".

Actually, I want to write file from service then send that file via email. Pls help me achieve that.

lcukerd
  • 31
  • 5

1 Answers1

1

Use the following code,

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
emailIntent.setType("*/*");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"me@gmail.com"}); 
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, 
"Test Subject"); 
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, 
"go on read the emails");     
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromfile(new File(yourtextfilepath));
startActivity(Intent.createChooser(emailIntent, "Send mail..."));

Make sure that your text file path should be from external memory card. Action send wont accept the files from internal memory. Also try this also, Link 1

Sunisha Guptan
  • 1,555
  • 17
  • 44