[SalesForce] Files as email attachment from Apex

We have a requirement to send email with attachment.
When a Opportunity stage is changed need to send a email to opportunity owner with attachments(Files added to that opportunity).

This work fine when attachments are added in salesforce classic and email will be sent to with attachments. But when we 'Upload File' in Notes And Attachment in partner community or lightning attachments are not added to the email. Because in partner community or in lightning attachments are added as ContentDocumnet.

Can any help us to add attach ContentDocument file in attachment.

Best Answer

If you have the ContentDocument Id you can fetch the ContentVersion file as this:

// If you only want the ContentVersion ID's
Map<Id, ContentVersion> contentVersions = new Map<Id, ContentVersion> {};
Set<Id> versionsToAttach = new Set<Id> {};
contentVersions.putAll([ 
    SELECT Id, ContentDocumentId 
    FROM ContentVersion 
    WHERE ContentDocument IN :contentDocumentIds 
]);

return contentVersions.keySet();

Then you can linked them as EmailFileAttachment:

List<Messaging.EmailFileAttachment> attachments = new List<Messaging.EmailFileAttachment>{};
List<ContentVersion> documents                  = new List<ContentVersion>{};

documents.addAll([
  SELECT Id, Title, FileType, VersionData, isLatest, ContentDocumentId
  FROM ContentVersion
  WHERE isLatest = true AND ContentDocumentId IN :new List<Id>(files)
]);

for (ContentVersion document: documents) {
  Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();

  attachment.setBody(document.VersionData);
  attachment.setFileName(document.Title);

  attachments.add(attachment);
}

Edit: ofc you can mix both code, I just picked part of mine as example but do everything in one SOQL query

Edit²:

public static List<Messaging.EmailFileAttachment> ContentDocumentAsAttachement(Id[] contentDocumentIds) {
    List<Messaging.EmailFileAttachment> attachments = new List<Messaging.EmailFileAttachment>{};
    List<ContentVersion> documents                  = new List<ContentVersion>{};

    documents.addAll([
      SELECT Id, Title, FileType, VersionData, isLatest, ContentDocumentId
      FROM ContentVersion
      WHERE isLatest = true AND ContentDocumentId IN :contentDocumentIds
    ]);

    for (ContentVersion document: documents) {
      Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();

      attachment.setBody(document.VersionData);
      attachment.setFileName(document.Title);

      attachments.add(attachment);
    }

    return attachments;

}

You can attach those Messaging.EmailFileAttachment with public Void setFileAttachments(EmailFileAttachment[] fileNames)

Or only the Ids with public void setEntityAttachments(List<String> ids)

Related Topic