I am able to attach a text file to an email with this code:
String fileName = "test.txt";
path = "file://" + Environment.getExternalStorageDirectory() + "/" + fileName;
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
startActivity(Intent.createChooser(sendIntent, "Email"));
However, emails sent through gmail do not contain the attachment if fileName="test#.txt".
I tried Encoding the path with URLEncoder, as below, but this doesn’t work with either “text.txt” or “text#.txt”.
I’m probably missing something simple here, but how should I encode file paths with special characters for send intents?
String fileName = "test.txt";
// String fileName = "test#.txt";
String path = "file://" + Environment.getExternalStorageDirectory() + "/" + fileName;
String encPath = URLEncoder.encode(path);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(encPath));
startActivity(Intent.createChooser(sendIntent, "Email"));
That’s because you didn’t encode the URL correctly. Instead of only encoding the filename, you encoded the full URL, which results in:
Try this instead: