1

I am trying to send an E-Mail with an Excel Attachment. Everything works, except I am getting a warning when I am trying to open the send attachment:

The file format and extension of 'ExcelfileSC.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?

Here is the relevant part of my code:

Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.ContentType = 'application/vnd.ms-excel; charset=UTF-8';
blob excel = blob.valueOf('\uFEFF'+finalstr);
attach.setBody(excel);
attach.setFileName('ExcelfileSC.xls');

I am setting the right filename and contenttype, so why does the format + extension not match?

2
  • What if you leave off the\uFEFF prefix? Jul 13, 2017 at 11:53
  • Same error, the prefix is just for utf-8 Jul 13, 2017 at 12:01

1 Answer 1

4

Excel is warning you that the internal structure of the file is not a real Excel Workbook format. The software is intelligent enough to recognize that it is something else (I presume you're rendering HTML/XML) and knows how to display/modify the contents, but the file itself is not an XLS file, which has specific headers and a binary format. It doesn't matter if ContentType and the file extension agree, this error is only concerned about the file's extension versus the actual contents of the file. As an example, if I hand you a file called "dancing-cats.gif", you open the file in a text editor, and you see a "JFIF" tag, you might realize that the file is not a GIF, but instead most likely a JPEG.

5
  • Ah, I understand. In fact it's not html/xml but a "self generated" excel. Put together like "Objekt \n';". Is there a way to put in the right headers and the right binary format? Jul 13, 2017 at 12:02
  • @FrederikWitte Realistically... no. The XLS format is not externally documented by Microsoft. You could theoretically use XLSX, but even though it's documented, it's also a pain to do in Apex because of a lack of binary conversion code. Your best bet sounds like you'd want to just call it a "CSV" instead.
    – sfdcfox
    Jul 13, 2017 at 12:05
  • Cheers, thanks for your help! So I will either go for CSV or somehow make a nice pdf out of it Jul 13, 2017 at 12:15
  • @FrederikWitte If you want Excel to open it properly with the XLS extension, you can try rendering it in HTML (<html><body>...</body></html>), but it's not well documented and mostly obsolete according to Microsoft. If you want it to be editable, CSV would be ideal. PDF isn't too bad to do either, but you'll still be rendering HTML.
    – sfdcfox
    Jul 13, 2017 at 12:26
  • There's an absurdly-complicated option for rendering an actual xls file from Visualforce, but it's the only way I've found that works. Link here: salesforce.stackexchange.com/questions/235368/… Nov 2, 2018 at 5:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .