Java – Android – Failed to send TXT file as email attachment (“Couldn’t send attachment”)

Android – Failed to send TXT file as email attachment (“Couldn’t send attachment”)… here is a solution to the problem.

Android – Failed to send TXT file as email attachment (“Couldn’t send attachment”)

I’m trying to get my Android app to send an email with an attachment, I start with an .txt file because these are simple.

So far I’ve had this (happening inside fragment

):

//Send the email
Intent mailIntent = new Intent(Intent.ACTION_SEND);
mailIntent.setType("text/Message");
mailIntent.putExtra(Intent.EXTRA_EMAIL  , new String[]{address});
mailIntent.putExtra(Intent.EXTRA_SUBJECT, "Test Email");
mailIntent.putExtra(Intent.EXTRA_TEXT   , "Hi!  This is a test!");

Deal with the attached report
String FileName = "report.txt";
Calculator.generateReport(getActivity().getApplicationContext(), FileName);
It will be called "report.txt"
File attachment = getActivity().getApplicationContext().getFileStreamPath(FileName);
if (!attachment.exists() || !attachment.canRead()) {
    Toast.makeText(getActivity().getApplicationContext(), 
                   "Attachment Error", 
                   Toast.LENGTH_SHORT).show();
    System.out.println("ATTACHMENT ERROR");
}
else
{
    Uri uri = Uri.fromFile(attachment);
    mailIntent.putExtra(Intent.EXTRA_STREAM, uri);
}

Send, if valid!
try {
   startActivity(Intent.createChooser(mailIntent, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(getActivity().getApplicationContext(), 
               "There are no email clients installed.", 
               Toast.LENGTH_SHORT).show();
}

Unfortunately, this doesn’t seem to work. Now I know the file exists; If I insert the appropriate code after generateReport(), I can find and access the file and read its contents. It’s there and I have the right name.

When I can choose an email client, I choose Gmail and see that there is indeed a report.txt file attached to the email. However, when I send an email, I get a notification that says “Unable to send attachment” and the email arrives without any attachments.

I

should point out that I’ve also tried other intent types like text/plain and message/rfc822, but to no avail.

Any thoughts on what I might have done wrong?

Solution

If you save the file as a private file of the application, the application can see if it works, but external email clients will not be able to see it.

You need to write it out to external storage, or make it public.

Use http://developer.android.com/reference/android/content/Context.html#MODE_WORLD_READABLE or http://developer.android.com/guide/topics/data/data-storage.html

Related Problems and Solutions