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
Ryan O'SullivanRyan O'Sullivan 

Converting a SingleEmailMessage to an Attachment

Hey,

I am trying to find a way to create a SingleEmailMessage using a template, send the email out but also take the filled in body ( the template body but with all the merge fields filled in) convert that to a blob and use that to make an attachment on the related Contract object.

Any Advice?

 
Best Answer chosen by Ryan O'Sullivan
Ryan O'SullivanRyan O'Sullivan
Ended up solving this problem using the RenderEmailTemplate method as such:

            // Render the Email into a string in order to save it as an attachment on the Contract
            List<Messaging.RenderEmailTemplateBodyResult> templateResults =
                Messaging.renderEmailTemplate(call.oContract.Delinquency_Recipient_1__c, call.oContract.Id,
                new String[]{emailTempQuery[0].body});

            // Go through results, and create attachments from them    
            for(Messaging.RenderEmailTemplateBodyResult result:templateResults){
                if(result.getSuccess()){
                    // Render was successful
                    Blob attachmentBlob = Blob.valueOf(result.getMergedBody());
                    newAttachments.add(new Attachment(Body = attachmentBlob, ParentId = call.oContract.Id,
                        Name = emailTempQuery[0].name));
                } else {
                    System.debug('Failed to render email template');
                }
            }

All Answers

BM 5BM 5
Below is the sample template 

Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.Body = attch.Body;
efa.FileName = attch.Name;
efa.ContentType = attch.ContentType

Thanks,
BM
 
Ryan O'SullivanRyan O'Sullivan
Ended up solving this problem using the RenderEmailTemplate method as such:

            // Render the Email into a string in order to save it as an attachment on the Contract
            List<Messaging.RenderEmailTemplateBodyResult> templateResults =
                Messaging.renderEmailTemplate(call.oContract.Delinquency_Recipient_1__c, call.oContract.Id,
                new String[]{emailTempQuery[0].body});

            // Go through results, and create attachments from them    
            for(Messaging.RenderEmailTemplateBodyResult result:templateResults){
                if(result.getSuccess()){
                    // Render was successful
                    Blob attachmentBlob = Blob.valueOf(result.getMergedBody());
                    newAttachments.add(new Attachment(Body = attachmentBlob, ParentId = call.oContract.Id,
                        Name = emailTempQuery[0].name));
                } else {
                    System.debug('Failed to render email template');
                }
            }
This was selected as the best answer