How To Send Email Along with PDF Document Attached

How To Send Email Along with PDF Document Attached

Introduction

It facilitates the sending of emails with dynamically generated PDF attachments. This functionality is particularly useful in scenarios where specific information needs to be communicated in a structured and printable format, such as invoices or welcome letters.

Key Features:

  1. Queueable Interface: Implements the Queueable interface to handle the processing asynchronously, ensuring that the main thread is not blocked and allowing for more complex operations without hitting governor limits.
  2. AllowsCallouts Interface: Implements the Database. The AllowsCallouts interface enables the execution of callouts to external systems during the email generation process, if necessary.
  3. Invocable Method: This package includes an invocable method, processRequest, which can be called from Salesforce Flow. This makes it easy to integrate this functionality into various business processes without writing additional code.
  4. PDF Attachment: Generates PDF documents from Visualforce pages, ensuring the information is formatted correctly and consistently.
  1. Dynamic Email Content: Salesforce’s Messaging API creates and sends emails, allowing for customization of the email content, including dynamic recipient lists and personalized messages.

How It Works:

Request Handling:

The processRequest method is exposed as an invocable method that takes a list of RequestParam objects. Each RequestParam contains a new version of an SObject, which represents the data needed for the email and PDF generation.

 

This method enqueues a new job, creating an instance of the SendingEmailAlongwithPdfAttached class with the provided request parameters.

Asynchronous Processing:

The Salesforce platform calls the execute method when the job is processed. It extracts the relevant data from the listRequests and calls the sendEmailToLeadUser method to handle the actual email sending.

PDF Generation and Email Sending:

For each request, the sendEmailToLeadUser method retrieves the necessary data, generates a PDF from a Visualforce page, and attaches it to an email.

The email is then customized with the recipient’s information and sent using the Messaging.sendEmail method.

Example Use Case:

Consider a scenario where a company needs to send personalized welcome emails to new leads, including a PDF attachment with detailed onboarding information. Integrating this class with a Salesforce Flow allows the company to automate this process, ensuring that every new lead receives the appropriate information without manual intervention.

Flow :

Flow

Code:

public class SendingEmailAlongwithPdfAttached implements Queueable,Database.AllowsCallouts{

            public List<RequestParam> listRequests;

            @InvocableMethod(label = ‘Send Email From Flow With Pdf Attached’

                         description = ‘Send Email From Flow With Pdf Attached’

                         category = ‘Send Email From Flow With Pdf Attached’)

            public static void processRequest(List < RequestParam > listRequests) {

            System.enqueueJob(new SendingEmailAlongwithPdfAttached(listRequests));     

            }

            public SendingEmailAlongwithPdfAttached(List<RequestParam> listRequests){

            this.listRequests = listRequests;

            }

            public class RequestParam {     

            @InvocableVariable(label = ‘1 New version of SObjects’

                          description = ‘@requires SEND_EMAIL_TO_LEAD_PERSONS’

                          required = false)

            public SObject objNewSObject;             

            }

            public void execute(QueueableContext context) {

            List < RequestParam > listParams = new List<RequestParam>();

            for (RequestParam objRequest: listRequests) {

             listParams.add(objRequest);

            }

            sendEmailToLeadUser(listParams);

            }

            private static void sendEmailToLeadUser(List < RequestParam > listRequests){

        List<Messaging.SingleEmailMessage> listEmailMessages = new List<Messaging.SingleEmailMessage>();

            Messaging.EmailFileAttachment emailFileAttachment;

            set<Id> LeadIds = new set<Id>();

            String[] toAddresses = new String[] {‘lokesh.bothsa@absyz.com’};

             String[] ccAddresses = new String[] {‘bothsalokesh9@gmail.com’};

            for (RequestParam objRequest : listRequests) {             

                         LeadIds.add( (Id) objRequest.objNewSObject.get(‘Id’));

            }

            List<Lead> listOfLeadRecords = [SELECT Id,Name,Email,CreatedDate,Owner.Name FROM Lead where Id in:LeadIds];

            Map<Id,string> mapIdVsEmails = new map<Id,string>();

            for(Lead eachLead : listOfLeadRecords){

            mapIdVsEmails.put(eachLead.Id,eachLead.Owner.Name);

             PageReference pr = new PageReference(‘/apex/SampleWelcomeEmailTemplate’);           

             pr.getParameters().put(‘id’, eachLead.Id);

             Blob pdf = pr.getContentAsPDF();

             emailFileAttachment = new Messaging.EmailFileAttachment();

            emailFileAttachment.setContentType(‘application/pdf’);

            emailFileAttachment.setFileName(eachLead.Name+’ ‘+eachLead.CreatedDate);

             emailFileAttachment.setBody(pdf);

            }

            for (RequestParam objRequest : listRequests) {

             Messaging.SingleEmailMessage enrollUser = new Messaging.SingleEmailMessage();

             enrollUser.setSubject(‘Welcome Email : ‘+mapIdVsEmails.get((Id) objRequest.objNewSObject.get(‘Id’)));

            enrollUser.setToAddresses(toAddresses);

            enrollUser.setCcAddresses(ccAddresses);

             enrollUser.setPlainTextBody(‘Hello, \nI Hope you are doing good! Please find your attachment’);

             enrollUser.setFileAttachments(new Messaging.EmailFileAttachment[] {emailFileAttachment});

            listEmailMessages.add(enrollUser);        

            }

            List<Messaging.SendEmailResult> listEmailResults = Messaging.sendEmail(listEmailMessages);

            } 

}

Visualforce Page Code:

<apex:page showHeader=”false”

           sidebar=”false”

           standardStylesheets=”false”

           applyHtmlTag=”false”

           renderAs=”pdf”>

    <body>

        <div style=”padding:0px;”>

             Welcome!

        </div>

    </body>

</apex:page>

Output:

Author: Lokesh Bothsa

Leave a Comment

Your email address will not be published. Required fields are marked *

Recent Posts

How To Send Email Along with PDF Document Attached
How To Send Email Along with PDF Document Attached
Agentforce 2dx role in industries (2)
Agentforce 2dx Role In Industries
Mastering Lightning Message Service (LMS) in LWC- A Comprehensive Guide
Mastering Lightning Message Service (LMS) in LWC: A Comprehensive Guide
Boost Your Testing Strategy- The Power of Automation and Frameworks
Boost Your Testing Strategy: The Power of Automation and Frameworks
FSC Blog- On Behavioural buying
Using Behavior-Based Segmentation to Recommend Financial Products That Fit Customer Life Stages
Scroll to Top