I am trying to get the Blob Version Data from the ContentVersion in Apex class and send it in an Email using the Following Code:

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      Messaging.Emailfileattachment efa1 = new Messaging.Emailfileattachment();
    if(typeo == 'SalesForce Error')
         List<id> ContentDocumentids = new List<id>();

         for(contentDocumentLink CDLink : [SELECT LinkedEntityid, ContentDocumentid FROM contentDocumentLink WHERE LinkedEntityid=:RecordID])
    /* GET Data for the image */
    ContentVersion cv = [SELECT title,PathOnClient, FileType,
                                          FROM contentversion 
                                          WHERE ContentDocumentId IN :ContentDocumentids  
          Blob Data = cv.VersionData;
          Mail.fileattachments.add(efa1); // This line is throwing the Error 

I have confirmed that there is in fact a file related to the ID that's being sent out but for some reason it's giving me the following Error:

execution of AfterUpdate caused by System.NullPointerException: Attempt to de-reference a null object 

What am I doing wrong? am I using the wrong information for attachment

UPDATE-- Afer doing Checkpoints I see there is Data in CV, but Mail.addatt atchment isnt able to add, it keeps showing null values see image below:

enter image description here?

  • Which specific line is throwing the error? Please edit your post to include more context -- is this a trigger? Apr 20 at 4:50
  • your strategy is not correct -- you want the LatestContentVersion for the CDL's ContentDocument
    – cropredy
    Apr 20 at 15:18
  • @DavidCheng Thanks for asking me to add info, I have edited the question, showing the line and what am I using to make this process happen. Apr 20 at 17:35
  • please use edit and properly format/indent your code
    – cropredy
    Apr 20 at 18:47
  • Hi @cropredy, I just added more information. Apr 20 at 18:50

Okay I figured it out, I was using a SingleEmailMessage object, and according to this documentation I have to add an attachment using the following code:

email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

instead of doing Mail. attachment

This worked!

Not the answer you're looking for? Browse other questions tagged or ask your own question.