Skip to content

Instantly share code, notes, and snippets.

@iamsonal
Last active August 31, 2022 02:57
Show Gist options
  • Save iamsonal/3ccd44b319724f4d03cdb4df0bde54d0 to your computer and use it in GitHub Desktop.
Save iamsonal/3ccd44b319724f4d03cdb4df0bde54d0 to your computer and use it in GitHub Desktop.
public static void sendEmail(Map<Id, Order> orderMap) {
List<ContentDocumentLink> contentDocumentLinks = [
SELECT Id, ContentDocumentId, LinkedEntityId
FROM ContentDocumentLink
WHERE LinkedEntityId IN :orderMap.keySet()
];
Map<Id, List<ContentDocumentLink>> contentDocumentLinksByOrderId = new Map<Id, List<ContentDocumentLink>>();
Set<Id> contentDocumentIds = new Set<Id>();
for (ContentDocumentLink contentDocumentLink : contentDocumentLinks) {
if (contentDocumentLinksByOrderId.containsKey(contentDocumentLink.LinkedEntityId)) {
List<ContentDocumentLink> tempContentDocumentLinks = contentDocumentLinksByOrderId.get(contentDocumentLink.LinkedEntityId);
tempContentDocumentLinks.add(contentDocumentLink);
contentDocumentLinksByOrderId.put(contentDocumentLink.LinkedEntityId, tempContentDocumentLinks);
} else {
contentDocumentLinksByOrderId.put(contentDocumentLink.LinkedEntityId, new List<ContentDocumentLink>{ contentDocumentLink });
}
contentDocumentIds.add(contentDocumentLink.ContentDocumentId);
}
List<ContentVersion> contentVersions = [
SELECT Id, ContentDocumentId, PathOnClient
FROM ContentVersion
WHERE ContentDocumentId IN :contentDocumentIds AND IsLatest = TRUE
];
Map<Id, ContentVersion> contentVersionsByContentDocumentId = new Map<Id, ContentVersion>();
for (ContentVersion contentVersion : contentVersions) {
contentVersionsByContentDocumentId.put(contentVersion.ContentDocumentId, contentVersion);
}
EmailTemplate emailTemplate = [SELECT Id, Body, Subject FROM EmailTemplate WHERE DeveloperName = 'Demo_Team' LIMIT 1];
List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
for (Order order : orderMap.values()) {
List<String> entityAttachmentIds = new List<String>();
List<ContentDocumentLink> orderContentDocumentLinks = contentDocumentLinksByOrderId.get(order.Id);
if (orderContentDocumentLinks != null && orderContentDocumentLinks.size() > 0) {
for (ContentDocumentLink contentDocumentLink : orderContentDocumentLinks) {
ContentVersion contentVersion = contentVersionsByContentDocumentId.get(contentDocumentLink.ContentDocumentId);
entityAttachmentIds.add(contentVersion.Id);
}
}
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setEntityAttachments(entityAttachmentIds);
email.setPlainTextBody(Messaging.renderStoredEmailTemplate(emailTemplate.Id, UserInfo.getUserId(), order.Id).plainTextBody);
email.setSubject(emailTemplate.Subject);
email.setToAddresses(new List<String>{ '[email protected]' });
emailMessages.add(email);
}
Messaging.sendEmail(emailMessages);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment