Trigger to send a pdf along with email in Salesforce

Trigger to send a pdf along with email in Salesforce

Messaging.EmailFileAttachment can be used to trigger to send a pdf along with email in Salesforce.

Sample Trigger:

trigger sendEmail on Employee__c (after insert, after update)  {   
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    for(Employee__c e : trigger.new) {  
        Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
        attach.setContentType('application/pdf');
        attach.setFileName('Employee.pdf');
       
        String body;
       
        body = '<html><h1 style=\"text-align:center;\">Employee Information</h1><br/><br/><table align=\"center\"><tr><td>Employee Name</td><td>' + e.Name + '</td></tr><tr><td>Age</td><td>' + e.Age__c + '</td></tr><tr><td>State</td><td>' + e.State__c + '</td></tr><tr><td>City</td><td>' + e.City__c + '</td></tr></table></html>';
        System.debug('HTML is ' + body);
       
        attach.Body = Blob.toPDF(body);
               
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] { e.Email__c });
        mail.setSubject('PDF Generation');
        mail.setHtmlBody('PFA');
        mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });    
       
        mails.add(mail); 
    }
    if(!mails.isEmpty()) {
        Messaging.SendEmail(mails);
    }
}

Generated PDF:

Leave a Reply