I have an excel/csv as an attachment related to an EmailMessage. I want to read the csv, process the data and create certain records(of custom object) based on that data. I want to understand how I can read the attachment using apex?

What I am trying to do is, get the information from an attachment.

Attachment attachmentRecord = [Select Id,Body,ContentType from Attachment  WHERE ParentId =<my EmailMessageId>];
System.debug('a ' +attachmentRecord.Body);
System.debug('b '+attachmentRecord.Body.toString());

When I print the body, I get the output as :

a Blob[13381]

if I convert it to string(2nd debug statement) I get an error saying :

System.StringException: BLOB is not a valid UTF-8 string

I want to understand what am I doing wrong here.

  • 2
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    Commented Sep 1, 2021 at 19:48
  • Thank you for the inputs, I have included additional info in my question, hope it helps. Appreciate your help. Commented Sep 2, 2021 at 5:55
  • @AwaisAhamed file with which extension is actually this attachamnet? is it a plain text or it is an excel file with .xlsx format? Commented Sep 2, 2021 at 12:00
  • Its a csv file with .csv extension Commented Sep 2, 2021 at 12:33

1 Answer 1


I was able to read a csv file from attachment record, using below apex code:

Attachment attachmentRecord = [Select Id,Body,ContentType from Attachment  WHERE ParentId = <Parent Record Id>];
String csvAsString;
String[] csvFileLines;
csvAsString = attachmentRecord.Body.toString();
csvFileLines = csvAsString.split('\n'); 
for(Integer i=1;i<csvFileLines.size();i++){
   string[] csvRecordData = csvFileLines[i].split(',');
   System.debug('csvFileLines '+i+' '+csvRecordData[0]);
   System.debug('csvFileLines '+i+' '+csvRecordData[1]);
   System.debug('csvFileLines '+i+' '+csvRecordData[2]);
   System.debug('csvFileLines '+i+' '+csvRecordData[3]);

You must log in to answer this question.

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