You cannot attach a file from the internal storage directly for any security purpose, so first you need to copy this file from the internal to the external directory, and then send it by mail if you want to delete this file from the external storage in onActivityResult ().
Here is the code:
private File copyFileToExternal(String fileName) { File file = null; String newPath = Environment.getExternalStorageState()+"/folderName/"; try { File f = new File(newPath); f.mkdirs(); FileInputStream fin = openFileInput(fileName); FileOutputStream fos = new FileOutputStream(newPath + fileName); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = fin.read(buffer)) != -1) { fos.write(buffer, 0, len1); } fin.close(); fos.close(); file = new File(newPath + fileName); if (file.exists()) return file; } catch (Exception e) { } return null; }
Email sending method:
private void sendEmail(String email) { File file = new File(Environment.getExternalStorageState()+"/folderName/" + fileName+ ".xml"); Uri path = Uri.fromFile(file); Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("application/octet-stream"); intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); String to[] = { email }; intent.putExtra(Intent.EXTRA_EMAIL, to); intent.putExtra(Intent.EXTRA_TEXT, message); intent.putExtra(Intent.EXTRA_STREAM, path); startActivityForResult(Intent.createChooser(intent, "Send mail..."), 1222); }
and then
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1222) { File file = new File(Environment.getExternalStorageState()+"/folderName/" + fileName+ ".xml"); file.delete(); } }
Call this method as follows:
copyFileToExternal(filename + ".xml"); sendEmail(EmailId);
Shubham
source share