Sunday, July 2, 2017

Trigger to send a PDF along with email in Salesforce

Trigger to send a PDF along with email in Salesforce

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:




No comments:

Post a Comment