Created
October 13, 2018 16:09
-
-
Save Frelseren/105ea7574a2854df41c7bb1714e6145f to your computer and use it in GitHub Desktop.
The Apex class to send out the email with the attachments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global class DownloadAttachments { | |
/** | |
* Send out the startup object attachments to the specified email and save it as the activity | |
* @param {String} startupId The Id of the target startup object, which files we should attach to the email | |
* @param {String} emailAddress The email address of the recipient | |
*/ | |
global static void download(String startupId, String emailAddress) { | |
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); | |
// Set the recipient address | |
message.setToAddresses(new String[] { emailAddress }); | |
// Attach files to the message | |
List<Startup__c> startups = [SELECT Id, (SELECT Id FROM Attachments) FROM Startup__c WHERE Id = :startupId]; | |
if (!startups.isEmpty()) { | |
Set<Id> attachmentIds = (new Map<Id, SObject>(startups[0])).keySet(); | |
List<Attachment> files = [SELECT Name, Body, ContentType FROM Attachment WHERE Id IN :attachmentIds]; | |
} | |
List<Messaging.EmailFileAttachment> attachments = new List<Messaging.EmailFileAttachment>(); | |
for (Attachment file: files) { | |
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); | |
efa.setFileName(file.Name); | |
efa.setBody(file.Body); | |
efa.setContentType(file.ContentType); | |
attachments.add(efa); | |
} | |
message.setFileAttachments(attachments); | |
// Set the message template | |
List<EmailTemplate> templates = [SELECT Id, Subject, HtmlValue FROM EmailTemplate WHERE DeveloperName = 'InvestorMaterial']; | |
if (!templates.isEmpty()) { | |
message.setTemplateId(template[0].Id); | |
message.setSubject(template[0].Subject); | |
message.setHtmlBody(template[0].HtmlValue); | |
} | |
// Set the message sender address | |
List<OrgWideEmailAddress> addresses = [SELECT Id FROM OrgWideEmailAddress WHERE Address = '[email protected]']; | |
if (!addresses.isEmpty()) { | |
message.setOrgWideEmailAddressId(addresses[0].Id); | |
} | |
// Save the message as activity | |
List<Lead> leads = [SELECT Id FROM Lead WHERE Email = :emailAddress]; | |
if (!leads.isEmpty()) { | |
message. setTargetObjectId(leads[0].Id); | |
message.setSaveAsActivity(true); | |
} | |
// Send the message | |
try { | |
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { message }); | |
} catch (Exception e) { | |
throw e; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment