Sending Email Template as PDF attachement is one of the basic requirement in Salesforce application. This blog will give step by step information how to send Email Template as PDF attachement and as a email body both.
Steps for sending Email Template as attachment
- Create Email Template for Attachement
- Create Email Template for Email Body
- Create Apex Utility Class for sending email
- Test Functionality
1. Create Email Template for attachment
Create a email template using html. You can add styles using html and css in email template.
For this blog, I have tried to create below email. You can try based on your requirement.
Email Template Name : Profile
2. Create Email Template for cover letter or email body
Create a email template for email body of email which need to be sent to customer/user.
We can use any place holder to make dynamic population of values at runtime based on record.
I have added only one place holder {name} which is replaced in body of email before sending to user.
Email Template Name : Mail Cover Letter
3. Create Apex Utility Class for sending email
Let us create a apex class which will send email to customer/user. For this we can use below classes.
Messaging.EmailFileAttachment :
This will be used to create a PDF using email template’s html content. Below code is used to convert html into PDF.
attach.setContentType('application/pdf'); attach.Body = Blob.toPDF(body);
Messaging.SingleEmailMessage:
This class will be used to create email message. I have used HTML value of email template in code, but you can also directly use email template id in code using setTemplateId method.
Complete Apex Code
4. Test Functionality
Test above functionality by executing below code.
PDFGenerationService.generatePDF();
You can call this code from lightning component or batch apex.
Demo Page
References:
Other Related Post
Send Email Using Email Template and Apex
6 comments
[…] Send Email Template As PDF Attachment using Salesforce Apex […]
Hi Dhanik – as a non coder, I have been able to implement this code and it works perfectly.
I have run into a difficulty in that the email template(s) being used for both cover and pdf have merge fields in them. Research I’ve done indicates I need to add settargetobjectID and setwhatid but I just don’t seem to be able to place them correctly in relation to the code you’ve provided. Would you be able to assist please?
Hello Kerrianne,
Let us connect on Linkedin. I will help you with your issue.
Thank You,
Dhanik
Hi Dhanik, I got this article as very helpful for me while debug a issue. I also have requirement of merge fields in the pdf. Can you pls help me on this?
Hello Satabadi,
Please explain your requirement with an example. We can also connect and discuss on this.
Thank You,
Dhanik
Hi Dhanik,
Let me know how we can connect