Queueable interface can be used to attach a Salesforce Visualforce as PDF to an outgoing email from trigger.
Sample Visualforce page:
<apex:page standardController="Account">
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockSectionItem >Account Name</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >{!Account.Name}</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >Account Number</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >{!Account.AccountNumber}</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >Industry</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >{!Account.Industry}</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
Sample Trigger:
trigger AccountTrigger on Account ( after update ) {
System.enqueueJob( new EmailNotificationWithPDF( trigger.new ) );
}
Sample Queueable Interface:
public class EmailNotificationWithPDF implements Queueable, Database.AllowsCallouts {
List < Account > listAccounts;
public EmailNotificationWithPDF( List < Account > listAccounts ) {
this.listAccounts = listAccounts;
}
public void execute( QueueableContext qc ) {
List < Messaging.SingleEmailMessage > listMessages = new List < Messaging.SingleEmailMessage >();
for ( Account acc : listAccounts ) {
Messaging.SingleEmailMessage objMessage = new Messaging.SingleEmailMessage();
Messaging.EmailFileAttachment objAttachment = new Messaging.EmailFileAttachment();
objAttachment.setContentType( 'application/pdf' );
objAttachment.setFileName( 'Sample.pdf' );
PageReference objPR = Page.AccountPage;
objPR.getParameters().put( 'id', acc.Id );
Blob emailBody = objPR.getcontentAsPdf();
objAttachment.Body = emailBody;
objMessage.setToAddresses( new String[] { '<Email Address>' } );
objMessage.setSubject( 'PDF Generation' );
objMessage.setHtmlBody( 'Please check the attachment' );
objMessage.setFileAttachments(
new Messaging.EmailFileAttachment[] { objAttachment }
);
listMessages.add( objMessage );
}
Messaging.sendEmail( listMessages );
}
}