function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chad RitchieChad Ritchie 

Attaching Salesforce File to Visualforce Email

Hey guys,

Is it possible to attach a file, a PDF that appears under the "Files" related object, to an email??? Ideally if I'm using visualforce and the email is being triggering off of a change on the Opportunity object, I'd like to send an email and attach all the files that appear under the "Files" object on that opportunity. Is this possible, and if so how difficult would this be to achieve? Thanks!!
karthikeyan perumalkarthikeyan perumal
Hello, 

Yes, its possible to do that.  Steps to follow, 

 1. while trigger collect Opp ID add it in to list, 
2. use SOQL Query to fetch list of files it related to opp's
use this query
( SELECT ContentDocumentId, LinkedEntityId  FROM ContentDocumentLink where LinkedEntityId in ( SELECT Id FROM Opportunity) and LinkedEntity.Type='Opportunity' )

OR 

 SELECT ContentDocumentId, LinkedEntityId  FROM ContentDocumentLink where LinkedEntityId in ( use list of IDs which you have for opp) and LinkedEntity.Type='Opportunity' 

3. user ContentDocumentId to get the Version data(Body or blob) data of the document.  use below query, 

(SELECT VersionData FROM ContentVersion WHERE ContentDocumentId = ContentDocumentId)

i think hereafter its easy to add attachment to email. you got all the things which you need. 

NOTE: normally files object stored in Content Document, ContentVersion, ContentDocumentLink
ContentDocument have  ContentDocumentId, 
ContentVersion have document data,
ContentDocumentLink is nothing but the file is related to which object like ( opp,case).

Hope this will be clear enough

Thanks
karthik


 
Chad RitchieChad Ritchie
@Karthikeyan Perumal, this is great information! I'm pretty new to Apex, if you are able to provide some code example of what you believe is needed to achieve this that'd be amazing!
Chad RitchieChad Ritchie
Here's what I have so far, but not sure if I'm on the right track. Thanks!

Trigger FileUpload on Opportunity (after insert, after update) {

    Set <String> oppID = New Set <String> ();
    For (Opportunity opp: Trigger.new) {
        if (con.OpportunityId != Null ) {
        oppID.add (opp.OpportunityId);
        }
    }
    If (oppID.size ()> 0) {
        List <Opportunity> upOppList = new List <Opportunity> ();
        For (Opportunity opp: (SELECT ContentDocumentId, LinkedEntityId  FROM ContentDocumentLink where LinkedEntityId in ( SELECT Id FROM Opportunity) and LinkedEntity.Type='Opportunity')) {
            Upo OppList.add (ac);
    
            If (oppID.size ()> 0) {
        List <Opportunity> upOppList = new List <Opportunity> ();
        For (Opportunity opp: (SELECT VersionData FROM ContentVersion WHERE ContentDocumentId = ContentDocumentId)) {
            Upo OppList.add (Opp);
           
    
    }
}