I have below utility class which throws error as this in debug log.
Error INVALID_FIELD_WHEN_USING_TEMPLATE: When a template is specified, the plain text body, html body, subject, charset, and "treatBodiesAsTemplate" may not be specified
Utility Class
public class AbbvieUtilitiesclass
{
public static Map<String,String> M;
/* public map<String, String> MyMap = new map<String, String> {'A' => 'Initial_Notification_to_Rep',
'B' => 'Initial_Notification_to_Manager_Publish',
'C' => 'Notify_DM_Manager_on_Incident_Closure',
'D'=> 'Reminder_Notification_to_Manager_and_RM',
'E'=>'Notify_Rep_on_Incident_Closure'};*/
public static void sendTemplatedEmail(String[] toRecipients, String[] ccRecipients,Boolean CCCheck, String templateApiName) {
// templateId must be ID of an Email template
// targetObjId must be a Contact, User, Lead Id -- also used in merge fields of template recipient.xxxx
// whatId must be an SObject that is used in the merge fields of the template relatedTo.xxxx
// fromId if non null, use current user, otherwise, use this ID (most likely an org wide no reply id)
// bcc not permitted when using templates
List < Messaging.SingleEmailMessage > mails = new List < Messaging.SingleEmailMessage > ();
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
Emailtemplate template;
try {template = [select Id, Subject, HtmlValue, Body, name from EmailTemplate where developername = : templateApiName];}
catch (Exception e) {
/*throw new UtilException ('[U-03] Unable to locate EmailTemplate using name: ' + templateApiName +
' refer to Setup | Communications Templates ' + templateApiName);*/
}
// String htmlBody = Template.HtmlValue;
// htmlBody = htmlBody.replace('{!}', 'Dear '+toRecipients );
email.setToAddresses(toRecipients);
if(CCCheck==true && templateApiname!='Initial_Notification_to_Manager_Publish')
{ email.setCcAddresses(ccRecipients);}
// email.setTargetObjectId(targetObjId);
//email.setWhatId(whatId);
// email.setorgWideEmailAddressId(orgWideEmailId);
email.setSubject(template.name);
// email.sethtmlbody(htmlbody);
//email.setTargetObjectId(targetid);
email.settemplateid(template.id);
email.setSenderDisplayName('Abbvie IT Team');
email.SetSaveAsActivity(false);
// email.setSaveAsActivity(saveAsActivity); // save email as activity on the targetObjId (i.e. Contact). Note activity can't be saved on Users
/* System.debug(LoggingLevel.INFO,'** entered sendTemplatedEmail, to:' + toRecipients + ' cc:' + ccRecipients + ' templateId:' + templateId + ' tagetObjId:' + targetObjId +
' whatId:' + whatId + ' orgWideEmailId: ' + orgWideEmailId);*/
try {
mails.add(email);
Messaging.sendEmail(mails);
return;
}
catch (EmailException e) {/*throw new UtilException('[U-02] sendTemplatedEmail error. ' + e.getMessage());*/}
}
}