function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Issue with Email templates



I wrote the trigger for sending email to contact when the case is opened.


I used the email template . In that , I need to pass my value of case number. So I tried like this {!Case.CaseNumber} in template.


But It dint show any case number.


I need to show the case number in subject using email templates and apex trigger.


Note :When Use the same email template in workflow rules , It works and shows the case number in subject.


But I am in need of apex trigger for sending email using templates which shows the case Number.


Please help to fix this problem.


Thanks & Regards.





1. The reason it works in workflow rules is that the workflow is already associated to a Case so the email alert has access to the Case being triggered. Email templates sent via APEX need a bit more help to make the association


2. This is my utility method for sending templated email:


    //	-------------------------------------------------------------------------
    //	sendTemplatedEmail
    //	-------------------------------------------------------------------------
    public static void sendTemplatedEmail(String[] toRecipients, String[] ccRecipients, String templateParmName, ID targetObjId, Id whatId, ID orgWideEmailId, Boolean saveAsActivity ) {
    	//	templateId 	must be ID of an Email template
    	//	targetObjId must be a Contact 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
    	Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
		String templateApiName = EnvironmentVariable.getString(templateParmName);
		Id templateId;	
		try {templateId = [select id, name from EmailTemplate where developername = : templateApiName].id;}
		catch (Exception e) {
			throw new MyException ('[UTIL-06] Unable to locate EmailTemplate using name: ' + templateApiName);
        email.setSaveAsActivity(saveAsActivity);			// save email as activity on the targetObjId (i.e. Contact)
        System.debug(LoggingLevel.INFO,'** entered sendTemplatedEmail, to:' + toRecipients + ' cc:' + ccRecipients +  ' templateId:' + templateId + ' targetObjId:' + targetObjId + 
        								' whatId:' + whatId + ' orgWideEmailId: ' + orgWideEmailId);
        try {
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        catch (EmailException e) {throw new MyException('[UTIL-07] sendTemplatedEmail error. ' + e.getMessage());}