Salesforce : visualforce page email template

The advantage of using Visualforce over standard HTML email templates is that Visualforce gives you the ability to perform advanced operations on data that is sent to a recipient.

E.g. as of now with HTML templates, we can just include data (using merge fields) from single or related records, think about a scenario where you need to send email with list of all contacts under an account. then how? use visualforce email template which you can customize with APEX code.

1) Go to My Templates and select email template as "Visualforce Page".

2) Once you save the template then following default code gets added to your template:

    <messaging:emailTemplate subject="Hello Me" recipientType="Contact" relatedToType="Account">
        <messaging:plainTextEmailBody >
            Congratulations!
            This is your new Visualforce Email Template.
        </messaging:plainTextEmailBody>
    </messaging:emailTemplate>



3) Develop an email template which sends list of all the contact under an account:

    Following is an example of :
        a) How to include component/apex code/custom feature  VF email template
        b) How to pass parameter to visualforce component?

4) Now if you have to add your custom code with this template then ?
    a) Create  your custom component ( with global access ) and add within messaging:plainTextEmailBody tag, as following

    Example :
    ===>Controller for component: FindContacts ( class )

            public with sharing class FindContacts {
                public String actId{get;set;}
                public List<Contact> getAccountContactList(){
                    return [select Name from Contact where AccountId= :actId order by createdDate desc LIMIT 10];   
                }
            }


    ===>Write a component as following: myAccountComp

            <apex:component controller="FindContacts" access="global">
                <apex:attribute name="accountId" type="string" assignTo="{!actId}" description="to fetch account contacts"/>
               
                <apex:repeat value="{!accountContactList}" var="cntRec">
                        *{!cntRec.Name}<br/>
                </apex:repeat>
            </apex:component>

   

    ===>VF Email Template Code:

    <messaging:emailTemplate subject="Hello Me" recipientType="Contact" relatedToType="Account">
        <messaging:htmlEmailBody >
            <c:myAccountComp accountId="{!relatedTo.Id}"/>
        </messaging:htmlEmailBody>
    </messaging:emailTemplate>



Email output includes many account record names, ( data from multiple record, you can query or process more data in controller )

Now configure an workflow with email  alert :), ( don't forget to email template ready for use and making workflow as active )

Comments

Popular Posts