[SalesForce] extract existing files from opportunities and send as an attachment in email

I have changed the SF file setting by checking the ‘Files uploaded to the Attachments….’ checkbox.
Loaded a file called test.pdf to an opportunity and noticed the title no longer contains the extension (‘.pdf’).

How can I attach the test.pdf file to an email?
I am able to loop through the content objects using :

 for (ContentDocumentLink docLinks : [Select Id from ContentDocumentLink where LinkedEntityId = :currentOppId ]) { 
     for (ContentDocument docs : [Select Id, FileType, Title from ContentDocument where ContentDocumentId = :docLinks]) {
     }
  }

Code that used to work:

    List<Messaging.Emailfileattachment> fileAttachments = new    List<Messaging.Emailfileattachment>();
 for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :currentOppId and (Name = 'test.pdf')]){
    // Add to attachment file list  
    Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
    efa.setFileName(a.Name); 
    efa.setBody(a.Body); 
    fileAttachments.add(efa);
 }
 mail.setFileAttachments(fileAttachments);

Best Answer

Please do the below changes : -

  1. query was right need to do in ContentDocumentLink.
  2. Need to change the second query , that query need to done in ContentVersion like belwo : -

    SELECT ContentDocumentId,VersionData,FileExtension,FileType,Id,Title FROM ContentVersion where ContentDocumentId = : //your content document Id from upper query

where you can find your file Name from Title and extension from FileType. And most important thing the body will stores in VersionData.

In your second portion of code no need to query in attachment.

In your second query put the below block : -

 List<Messaging.Emailfileattachment> fileAttachments = new    List<Messaging.Emailfileattachment>();
 for (This should be our second query and for loop will be done in ContentVersion){
    // Add to attachment file list  
    Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
    efa.setFileName(a.Title); //Title of the PDF
    efa.setBody(a.VersionData); //Body of the PDF,need to do transfer into blob
    fileAttachments.add(efa);
 }
 mail.setFileAttachments(fileAttachments);

this should work.