Android, .txt email attachment not sent using intent
I am testing creating a .txt file and then sending it as an email attachment using an intent.
Creating a .txt file
try {
String fileName = "testFileName.txt";
File root = new File(Environment.getExternalStorageDirectory(), "testDir");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, fileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append("Testing email txt attachment.");
writer.flush();
writer.close();
sendEmail(gpxfile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
Sending email
protected void sendEmail(String fileName){
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_SUBJECT, "Test subject");
i.putExtra(Intent.EXTRA_TEXT, "This is the body of the email");
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(fileName));
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
And it all works fine. It opens a mail client with visible object, body and attachment.
And only sends a fine, indicating that there is an attachment
But when I open gmail, the app doesn't show
Same story when I go through my email
And viewing email on the phone, from the Sent Items folder, also doesn't show attachments
The code is copy and paste from several different posts on SO and they don't seem to have any problems. Where does the file go? Is it stopped by gmail? Or not send at all? Doesn't the file exist?
Note. I have it <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
installed in the manifest.
Thanks in advance.
source to share
The problem was in the file path. The following changes have been made:
sendEmail(gpxfile); // This is the file itself, not the file path
Then we send by email:
protected void sendEmail(File file){
Uri path = Uri.fromFile(file); // This guy gets the job done!
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_SUBJECT, "Test subject");
i.putExtra(Intent.EXTRA_TEXT, "This is the body of the email");
i.putExtra(Intent.EXTRA_STREAM, path); // Include the path
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
source to share