I'm facing difficulties reading & parsing a CSV attachment that was sent to an email.

When I debug the code, the debugger writes empty lines between each new row, which to me looks like some kind of formatting/encoding issue.

//Get email attachments, parse it, and import lead records
if(email.textAttachments != null) {
    for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
        //parse attached file and create objects
        List<List<String>> csvRecords = CSVReader.readIETFRFC4180CSVFile(Blob.valueOf(tAttachment.Body));
        System.debug('csvRecords: ' + csvRecords);
        import(csvRecords, 'Lead');

I am trying to use Marty Chang's CSV Reader, but somehow this class is not working properly with CSV attachments fetched from emails.

I tried creating a new Document record in Salesforce, where I uploaded the same CSV file, and the CSV Reader worked flawlessly on that file. This tells me that the information is stored differently in a Document object, and in a TextAttachment object.

My CSV is super simple, it basically has 5 fields (all the required ones to create Leads), and there are no special characters in it. Not even spaces. I tried to make it as simple as possible.

Here's a screenshot of the debug log, when I try to parse the same file in an Attachment form and in a Document form: enter image description here

You can see that the Document body is displayed correctly, while the Attachment one has the empty lines between each row. This is possibly the cause for all my issues...

1 Answer 1


So if you sent in a super simple CSV such as this:


You should be able to do this then:

List<List<String>> csvRecords = CSVReader.readIETFRFC4180CSVFile(Blob.valueOf(attachmentAbove));

System.debug(csvRecords[0][0]);// This should output foo
System.debug(csvRecords[0][1]);// This should output bar
System.debug(csvRecords[1][0]);// This should output Hello
System.debug(csvRecords[1][1]);// This should output World

Can you please try that and see what happens

  • Problem was with the attachment not being seen the right way. By forcing the Email Service to convert it to Binary Attachment, the above mentioned code works. Thanks
    – Laureant
    Nov 19, 2019 at 15:57

You must log in to answer this question.

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