You need to sign in to do that
Don't have an account?
Hermann Ouré
Here is my full code:
Apex class:
Display Case Number on automatic email response with Email-to-Case
Hello,
I am trying to include a Case Number of an email template for an email-to-case.
Basically, when a client sent an email to a closed case, he received an automatic email reply.
On the template I have added the merge field value {!Case.CaseNumber}
but the Case Number does not appear on the email reply sent to the client
I believe that, to add the Case Number in the automatic email reply, I need to reference the CaseId somewhere in my code. But I have figured out how.
The tried to do
mail.setTargetObjectId(c.Id);But that does not work.
Here is my full code:
Apex class:
public class EmailManager { @future public static void sendEmailToCaseDeactivated(Set<Id> caseIds){ List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>(); List<Case> lstCase = [SELECT Id, Status,ContactEmail FROM Case WHERE Status = 'Closed' AND ContactEmail != Null AND Id IN: caseIds]; EmailTemplate templateId = [SELECT Id FROM EmailTemplate WHERE DeveloperName =:'Email_to_Case_Closed']; for(Case c : lstCase) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setTargetObjectId(UserInfo.getUserId()); mail.setTemplateId(templateId.Id); String[] sendingTo = new String[]{c.ContactEmail}; mail.setToAddresses(sendingTo); mail.setSaveAsActivity(false); allmsg.add(mail); } Messaging.sendEmail(allmsg, false); } }Apex Trigger:
trigger IncomingEmailClosedCase on EmailMessage (before insert,after insert) { if(trigger.isBefore) { Set<Id> sCaseIds = new Set<Id>(); for(EmailMessage em: Trigger.New) { if (em.Incoming) sCaseIds.add(em.parentId); } if(!sCaseIds.isEmpty()) EmailManager.sendEmailToCaseDeactivated(sCaseIds); } if(trigger.isAfter){ Map<Id,Id> caseIdsToEmailMessageIds = new Map<Id,Id>(); for(EmailMessage em: Trigger.New) { if (em.Incoming) caseIdsToEmailMessageIds.put(em.parentId,em.Id); } set<Id> sMessageIdsToDelete = new Set<Id>(); if(caseIdsToEmailMessageIds.isEmpty()) return; for(Case lstCase : [SELECT Id, Status,ContactEmail FROM Case WHERE Status = 'Closed' AND ContactEmail != Null AND Id IN: caseIdsToEmailMessageIds.keyset()]){ if(caseIdsToEmailMessageIds.containsKey(lstCase.Id)){ Id emId = caseIdsToEmailMessageIds.get(lstCase.Id); sMessageIdsToDelete.add(emId); } } if(!sMessageIdsToDelete.isEmpty()) delete [ select Id from EmailMessage where id in :sMessageIdsToDelete]; } }