How to setup Email templates with logic

Until now, when a field was changed we had an email sent to the relevant parties. Now, I am asked to use logic based on which field it changed, to send emails to specific people with the fields info contained in the email. So I can not just send an email saying xyz was changed but I must send the data from the document as well.

How to add logic (if then statements) to send an email and only show data from certain fields based on certain dates chosen? Apex would be fine.

Any examples would help.


If you are using set setTemplateId, instead I recommend you to use setHtmlBody and setPlainTextBody to set the body with the body of your email template. Additionally add some specific strings to the body of your template, like $$$Text_to_replace and replace that text with the correct info according to your logic.

Here is some guideline:

String mySelectedInfo = "...";//Info selected with if statements

EmailTemplate template = [SELECT Id, Subject, HtmlValue, Body
                          FROM EmailTemplate WHERE Id =: teamplateId];

template.HtmlValue.replace('$$$Text_to_replace', mySelectedInfo);
template.Body.replace('$$$Text_to_replace', mySelectedInfo);


Messaging.sendEmail(new Messaging.SingleEmailmessage[] {mail});

See Visualforce Templates. You can use most standard elements, except those mentioned in the help topic. If you need to use Apex Code as well, you need to create a Visualforce component to call the logic. Notably, you can use "rendered" attributes to show/hide information.

Category: apex Time: 2016-07-31 Views: 6
Tags: email apex

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.120 (s). 12 q(s)