Salesforce | Attach PDF from Visualforce page as an email attachment

Author - Webner

Problem: How to attach PDF from a Visualforce page in email using apex class or trigger?

Description: We had a Visualforce page name ‘templateCOI’ which was rendered as a PDF. We wanted to use this page as an attachment in the automated email on a trigger.

Solution: Here is the code for this problem:

In this example, an automated email is sent when payment status of the record is updated to ‘Paid’.

Code for trigger:

trigger CheckPaymentStatus on Object_Info__c (before update)
{
List TripsList = new  List();
for(Object_Info__c term : Trigger.new)
{
Object_Info__c oldOpp = Trigger.oldMap.get(term.Id);
if(term.Payment_Status__c =='Paid')
{
if(oldOpp.Payment_Status__c != term.Payment_Status__c)
{
sendPDfEmail.sendPDf(term.Id,term.Email__c);
}
}
}
}

Code for sending emailing and attaching Visualforce page in email:

public class sendPDfEmail
{
public static void sendPDf(String Id,String Email)
{
Messaging.SingleEmailMessage emailTobeSent = new Messaging.SingleEmailMessage();
PageReference PDf =  Page.templateCOI;//Replace attachmentPDf with the page you have rendered as PDF
PDf.getParameters().put('Id',Id);
PDf.setRedirect(true);
Attachment attach = new Attachment();
Blob b ;
b = PDf.getContent();
attach.Body = b;
attach.Name = 'Confirmation of product';
attach.IsPrivate = false;
attach.ParentId = Id;
insert attach;
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('Confirmation of product.PDf');
efa.setBody(b);
List  listEmailMembers = new List();
listEmailMembers.add(Email);
emailTobeSent.setToAddresses(listEmailMembers);
emailTobeSent.setSubject('Confirmation of product');
emailTobeSent.setHtmlBody('Hi');
emailTobeSent.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); // Sends the email
Messaging.SendEmailResult [] r1 = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {emailTobeSent});
}
}

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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