Unable to send email with attachments from my app

2019-07-24 07:28发布

问题:

I'm trying to send files (.log files) contained in a sdcard's folder using Intent. This is the code:

public void sendMail() {
            Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_EMAIL, new String[] {"name.surname@gmail.com"});
            intent.putExtra(Intent.EXTRA_SUBJECT, "Log files");
            intent.putExtra(Intent.EXTRA_TEXT, "body");
            //has to be an ArrayList
            ArrayList<Uri> uris = new ArrayList<Uri>();
            //convert from paths to Android friendly Parcelable Uri's
            if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
                File root = Environment.getExternalStorageDirectory();

                File logfolder = new File(root, "log");


                for (String file : logfolder.list()){
                    Uri u = Uri.parse(file);
                    uris.add(u);
                }
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                startActivity(Intent.createChooser(intent, new String("Send mail...")));
            }

        }

I choose Gmail from menu. Once Gmail is opend it displays a mail with recipient, subject, text, and attachment files correctly. The mail is sended with no error but i get a status bar notification that says "couldn't show attachment"! In fact recipient receives email correctly but it has no attachment. I'm not able to figure out what is the problem. Why attachments are not sended? Please help me!!

回答1:

Ok. i find the solution. Need to replace this:

for (String file : logfolder.list()){
   Uri u = Uri.parse(file);
   uris.add(u);
}

with this:

for (File file : logfolder.listFiles()){
    Uri u = Uri.fromFile(file);
    uris.add(u);
}