Search code examples
androidemailattachmentexcellibrary

Attach an XLS (Excel) file to Email


My application uses the intent method to send out emails to users, as a convenient way of exporting Excel spreadsheet data (created by the JExcell API).

The file is contained on the SD card in a folder called records.

The file I am attempting to send is call measurments.xls.

I have tested in code for the existence of the file prior to sending. The email composer shows an attachment, but when I send and then receive the email the attachment is not there.

However, if I substitute the excel file for a png image, the attachment is received. So what gives??

Below is the code I use to send out the email, it is simply a paramiterised static method in a class by its self.

    public static  void sendEmailWithAttachment(Context ctx, String to,String subject, String message, String fileAndLocation)
    {
        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
        emailIntent.setType("text/plain");
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {to}); 

        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,  subject); 
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,  message); 


          File file = new File(fileAndLocation);
         //  File file = getFileStreamPath();
           if (file.exists())
           {
               Log.v("Farmgraze", "Email file_exists!" );
           }
           else
           {
               Log.v("Farmgraze", "Email file does not exist!" );
           }


        Log.v("FarmGraze", "SEND EMAIL FileUri=" + Uri.parse("file:/"+ fileAndLocation));
        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:/"+  fileAndLocation));

        ctx.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
    }//end method

So what do I need to do to receive the xls file? Change the mime types in the second line of the method's code? If so what do. Any helpful advice would be greatly appreciated.

Thanks for reading.

A.

Solution

  • Ok folks just to add closure to this question I found the solution.

    The problem was that the file path String sent to the URI, needs to have three forward slashes.

    As in:

    file:///sdcard/somefolder/some_file.xls.
    

    Also for excel documents one needs to set the type as follows:

    emailIntent.setType("application/excel");
    

    So the problem was a two pronged one. I was aware of the three slash solution via this thread, but as it did not work thought the problem lie else where.

    Also I became aware of the correct mime types via this webpage which lists all of the supported mime types, and may be very useful for other readers.

    So thanks for reading and taking an interest in my little problem which is now solved.