Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ public without sharing class SendBetterEmail {

if (templateID != null && templateID.length() > 0) {
try {
mail.setTemplateID(templateID);
mail.setHtmlBody(SendBetterEmailUtil.renderTemplate(templateID, mail.targetObjectId, mail.whatId));
mail.setTreatTargetObjectAsRecipient(setTreatTargetObjectAsRecipient);
thisResponse.templateUsed = templateID;
} catch (Exception e) {
Expand Down Expand Up @@ -606,4 +606,4 @@ public without sharing class SendBetterEmail {

public class InvocableActionException extends Exception {
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -306,4 +306,63 @@ public inherited sharing class SendBetterEmailUtil {

return mapRecordIdByName;
}
}

public static String renderTemplate(
String templateId,
String targetObjectId,
String whatId
){
Messaging.SingleEmailMessage tempMail = new Messaging.SingleEmailMessage();

tempMail = Messaging.renderStoredEmailTemplate(templateID, targetObjectId, whatId);

Pattern pattern = Pattern.compile('###(.*?)###');
Matcher matcher = pattern.matcher(tempMail.htmlBody);
List<String> sObjectFields = new List<String>();
while (matcher.find()) {
sObjectFields.add(matcher.group(1));
}

String relatedEntityType = [SELECT RelatedEntityType FROM EmailTemplate WHERE Id = :templateID].RelatedEntityType;

Schema.SObjectType sObjectType = Schema.getGlobalDescribe().get(relatedEntityType);
if(sObjectFields.size() > 0 && whatId != null && sObjectType != null){
String query = 'SELECT ' + String.join(sObjectFields, ', ') + ' FROM ' + sObjectType + ' WHERE Id = \'' + whatId + '\'';
SObject sObjectRecord = Database.query(query);

matcher.reset();
while (matcher.find()) {
String field = matcher.group(1);
String[] fieldParts = field.split('\\.');
String fieldValue;

SObject obj = sObjectRecord;
for(Integer i = 0; i < fieldParts.size(); i++){
if(i + 1 != fieldParts.size()){
obj = obj.getSObject(fieldParts[i]);

if(obj == null){
break;
}
} else {
try{
fieldValue = (String) obj.get(fieldParts[i]);
} catch (TypeException e){
if (obj.get(fieldParts[i]) instanceof Date){
fieldValue = ((Date) obj.get(fieldParts[i])).format();
} else if(obj.get(fieldParts[i]) instanceof Datetime){
fieldValue = ((Datetime) obj.get(fieldParts[i])).format();
} else {
fieldValue = obj.get(fieldParts[i]).toString();
}
}
}
}

fieldValue = fieldValue == null ? '' : fieldValue;
tempMail.htmlBody = tempMail.htmlBody.replace(matcher.group(), fieldValue);
}
}
return tempMail.htmlBody;
}
}