Android - Sending TXT File as Attachment to Email Fails (“Couldn't send attachment”)

梦想的初衷 提交于 2020-01-14 14:32:08

问题


I am trying to get my Android app to send an e-mail with a file attached, and I'm starting out with a .txt file, since those are simple.

So far I have this (taking place inside a 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, that 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 is there, and I have the right name.

When I am given the option of choosing an email client, I pick Gmail and see that there is indeed a report.txt file attached to the email. When I send the email, though, I get a notification stating "Couldn't send attachment", and the email arrives without anything attached.

I should note that I have tried other intent types as well, such as text/plain and message/rfc822, to no avail.

Any ideas on what I might be doing wrong?


回答1:


If you have saved the file as being private to the app, the app can see if fine but the external email client will not be able to see it.

You'll 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




回答2:


https://stackoverflow.com/a/18548685/293280

The above SO answer for a really good walkthrough of copying the file, attaching it to the email, sending the email and, finally, deleting the copied file.



来源:https://stackoverflow.com/questions/15961409/android-sending-txt-file-as-attachment-to-email-fails-couldnt-send-attachme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!