When my users want to email me, I want to add an option where they can send me logs from the app. I would like to save some text in a text file and then send that text file as an attachment to the email the user is going to send to me.
I have tried the following two approaches.
Approach #1:
Calling the two functions below as follows:
copyFileToExternal("test_file_name" + ".xml");
sendEmail("nilashis@gmail.com", "test_file_name");
Below are the functions:
private File copyFileToExternal(String fileName) {
File file = null;
String newPath = Environment.getExternalStorageDirectory()+"/folderName/";
try {
File f = new File(newPath);
f.mkdirs();
FileInputStream fin = openFileInput(fileName);
FileOutputStream fos = new FileOutputStream(newPath + fileName);
//byte[] buffer = new byte[1024];
byte[] buffer = "safdsdfsdfsdfsdfdsf".getBytes();
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;
}
//Method to email
private void sendEmail(String email, String fileName) {
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, "This is the subject I want");
String to[] = { email };
intent.putExtra(Intent.EXTRA_EMAIL, to);
intent.putExtra(Intent.EXTRA_TEXT, "here is the message I want");
intent.putExtra(Intent.EXTRA_STREAM, path);
startActivityForResult(Intent.createChooser(intent, "Send mail..."),
1222);
}
Approach #2:
Does not work:
public void doSendFile() {
String xmlFilename = "fileToSend.txt";
FileOutputStream fos = null;
try {
fos = openFileOutput(xmlFilename, MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("this is test being written to ".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
// Uri uri = Uri.fromFile(new File(xmlFilename));
Uri uri = Uri.fromFile(new File("/mnt/sdcard/../.."+getFilesDir()+"/"+xmlFilename));
intent.putExtra(android.content.Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Send eMail..asdasd"));
}