Print this page

Send email templates via Visualforce and Apex

Knowledge Article Number 000181102
Description Scenario -
1) An email template with ID, say "XXXXXXXXXXX" is created via Administration Setup -> Communication templates -> Email Templates
2) VF page has a button created via <apex:commandButton> on an object, say Account.
3) When this button is clicked, email template created in step 1 should show up.

How can this be done?
Resolution //////////////CODE SNIPPET
1) Visualforce Page creating the button and showing it on Account.
emailHelper class is used to show the email template when the button is clicked.

<apex:page standardController="Account" extensions="emailHelper">
<apex:form >
<apex:commandButton action="{!sendEmail}" value="Send my email" id="theButton"/>
<apex:detail />

2) Apex class - emailHelper used to display the email template
public with sharing class emailHelper {
  // In a separate class so that it can be used elsewhere
public Account acct {get;set;}    
public User myUser { get;set;}

public emailHelper(ApexPages.StandardController stdController)
{ acct = (Account)stdController.getRecord(); 

User currentUser = [Select email from User where username = :UserInfo.getUserName() limit 1];  

public  PageReference sendEmail() {
PageReference emailPage = new PageReference('/email/author/emailauthor.jsp');
Map<String, String> params = emailPage.getParameters();
params.put('p3_lkid',acct.ID); //email will be attached to the activity history of the account where the button was clicked using the acct.ID
params.put('template_id','00Xd0000000XRBz'); /// template ID of the email template to be shown goes here
params.put('p24',currentUser.Email); //currentUser.Email showing in "Additional to" field
params.put('p5',''); //email address showing in Bcc field
params.put('retURL',ApexPages.currentPage().getUrl()); //after send button is clicked, go back to the account where the button was clicked
return emailPage;

promote demote