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
CyclebiffCyclebiff 

Cannot send email to Case Owner

Help!!

 

Issue: I have an APEX script that reassigns to a specific owner based on certain criteria (effectively bypassing Auto Assignment rules). This works fine, however I'm trying to code an emailCaseOwner(Case) function that emails the case owner after it's assigned. The trigger I'm passing is Case update before.  The email that is ultimately sent to the case.OwnerID is not populating the merge fields.

 

The email template is used as the "Case Assigned Template" (Setup -> Customize -> Case -> Support Settings). I'm basically mimicing the checkbox when manually assigning a case owner "Send Notification Email".

 

End result of email being sent to assigned user:

Force.com Sandbox

Case Number:  -

Client:  -  

Created by: 

Subject:

Description:

 

APEX Code:

    public static void emailCaseOwner(Case a)
    {
        EmailTemplate template = [select Id from EmailTemplate where Name = 'NewCase4CRC' limit 1];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(tempContact.Id);
        mail.setTemplateId(template.Id);
        mail.saveAsActivity = false;
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail } );
    }

Template Snippet:

Case Number: {!Case.CaseNumber} - {!Case.Product__c}
Client: {!Case.Contact} - {!Case.Account} {!Contact.Phone} {!Contact.Email}
Created by: {!Case.CreatedBy} {!Case.CreatedDate}

{!Case.Link}

Subject: {!Case.Subject}

Description: {!Case.Description}

TraceyTracey
I'm having a similiar problem
CyclebiffCyclebiff
What exactly are you having issues / errors with? Can you post your APEX code?
TraceyTracey
Hi
 
This is the error that I'm getting. below is the code that I'm using 
SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.
 
public class StepstoneInternalCaseComment {//Assigned_Developer__c//Assigned_Developer__c//Select c.Name, c.Id From CaseTeamRole c//where Name = 'Receive Internal Notifications'//Select c.TeamRoleId, c.ParentId, c.MemberId, c.Id From CaseTeamMember c///Select u.Name, u.Id, u.Profile.Name From User u//Case Owner//Related User: Assigned Developer//Related User: LastCaseComment_CreatedBy//Case Team: Receive Internal Notifications   public  StepstoneInternalCaseComment (List<Case> casedata )   {   	   		//  InternalLog__c  Ilg1 = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.Start', Type__c = 'Information', Description__c = 'Starting ..........');     // insert (Ilg1);   	   	          for ( Case c : casedata)        {                    sendInternalCaseCommentNotification(c);            InternalLog__c  Ilg2 = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.StepstoneInternalCaseComment', Type__c = 'Information', Description__c = 'Start - Case No ' + c.CaseNumber);            insert (Ilg2);       }      //  MassDeleteInternalLogs();   	   }      public void sendInternalCaseCommentNotification(Case ccase){        System.debug('#sendInternalCaseCommentNotification');        ID emailTemplateId = GetEmailTemplateCaseCommentforInternalUsersId();        System.debug('#sendInternalCaseCommentNotification - Email Template ID' + emailTemplateId );        InternalLog__c  Ilg1 = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.sendInternalCaseCommentNotificationEmailTemplateId', Type__c = 'Information', Description__c = 'Email Template ID : ' + emailTemplateId);        insert (Ilg1);        ID[] ContactIds = GetInternalNoficationsContactIds(ccase);                InternalLog__c  Ilg2 = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.sendInternalCaseCommentNotification', Type__c = 'Information', Description__c = 'Case No ' + ccase.CaseNumber);        insert (Ilg2);                sendMassEmail (ccase , ContactIds,emailTemplateId);    }        public void sendMassEmail(Case ccase, ID[] contactIds,  Id emailTemplateId)    {      System.debug('#sendMassEmail + no of contacts ' + contactIds.size());      Messaging.SingleEmailMessage[] messages = new Messaging.SingleEmailMessage[contactIds.size()];      for (Integer i = 0; i < contactIds.size(); i++)      {         try{                    System.debug('#sendMassEmail + contact Id ' + contactIds[i]);          Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();                           ///00XR0000000QP1Z         //00XR0000000QPcp          emailTemplateId = '00XR0000000QPcp';          message.setTemplateId('00XR0000000QPcp');          message.setTargetObjectId(contactIds[i]);   		//  message.setWhatid(ccase.Id);   		  message.setSaveAsActivity(false);    		     		   		     		  InternalLog__c  Ilg1 = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.sendMassEmail', Type__c = 'Information', Description__c = ccase.id + ' , ' + emailTemplateId +' , ' + contactIds[i] );          insert (Ilg1);   		  SendSingleEmail(ccase,contactIds[i],emailTemplateId );         }         catch (Exception e)         {          		InternalLog__c  Ilg2 = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.sendMassEmailException', Type__c = 'Information', Description__c = e.getMessage() );          		insert(Ilg2);         }         // messages[i] = message;                }                    /*****          Try{            Messaging.sendEmail(messages);            InternalLog__c  Ilg2 = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.sendMassEmail', Type__c = 'Information', Description__c = 'Sending Mass Email - No = ' + messages.size());            insert (Ilg2);          }          catch(Exception e)           {               System.debug('# sendMassEmail - Messaging.sendEmail Exception ' );          }       *****/    }         public void SendSingleEmail(Case ccase ,  ID contactId, Id emailTemplateId){   		   		Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();   		   		InternalLog__c  Ilg = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.SendSingleEmail', Type__c = 'Information', Description__c = 'Case Id : ' + ccase.Id +' ContactId = ' + contactId );        insert (Ilg);           		mail.setTargetObjectId(contactId);   		mail.setWhatId(ccase.Id);   		mail.setTemplateId(emailTemplateId);   		mail.setSaveAsActivity(false);   		//setSaveAsActivity(true);   		   		Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });   	}   	   	      public String GetProfileName (string ProfileId){        String pname = null;        for (Profile pr : [Select p.Name, p.Id From Profile p  where p.Id = : ProfileId ]){              pname = pr.Name;              System.debug('#GetProfileName : ' + pname );              InternalLog__c  Ilg = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.GetProfileName', Type__c = 'Information', Description__c = 'ProfileId : ' + ProfileId);              insert (Ilg);        }                return pname;    }    public ID GetEmailTemplateCaseCommentforInternalUsersId(){        Id etId = null;        for (EmailTemplate etdata : [Select e.Name, e.Id, e.CreatedDate From EmailTemplate e where e.Name = 'Case Comment for Internal Users' limit 1]){              etid = etdata.id;              System.debug('#GetEmailTemplateCaseCommentforInternalUsersId : ' + etId );              InternalLog__c  Ilg = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.GetEmailTemplateCaseCommentforInternalUsersId', Type__c = 'Information', Description__c = 'Case Team Members');              insert (Ilg);        }                return etId;    }        public ID GetCaseTeamRoleIdforInternalNotificatonId(){        Id ctrId = null;        for (CaseTeamRole ctrdata : [Select c.Name, c.Id From CaseTeamRole c where c.Name = 'Receive Internal Notifications' limit 1]){              ctrid = ctrdata.id;              System.debug('#GetCaseTeemRoleIdforInternalNotificatonID : ' + ctrid );        }                return ctrId;    }    /****     public void setProducts() {        List<String> productNamesList = new List<String>();        // get all the products that relate to products referenced by the trigger        for(Product2 product2 : [SELECT Id, Name, Product_Director__c  FROM Product2 WHERE Name IN :productNameSet]) {   ****/        public List<ID> GetInternalNoficationsContactIds(Case ccase)    {        List<ID> INCIds = new List<ID>();                 InternalLog__c  Ilg = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.GetInternalNoficationsContactIds', Type__c = 'Information', Description__c = 'Starting proc');         insert (Ilg);                for (CaseTeamMember ctmdata : [Select c.TeamRoleId, c.ParentId, c.MemberId, c.Id From CaseTeamMember c where c.ParentId = : ccase.id]){             INCIds.add(ctmdata.MemberId);             System.debug('#GetInternalNoficationsContactIds : ' + ctmdata.MemberId );        }          if (ccase.Assigned_Developer__c != null)        {           INCIds.add(ccase.Assigned_Developer__c);        }        if (ccase.IsPortalUser__c == 'Y')        {            INCIds.add(ccase.ownerid);        }        If (ccase.LastCaseComment_CreatedBy__c != null)        {            INCIds.add(ccase.LastCaseComment_CreatedBy__c);        }         InternalLog__c  Ilg1 = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.GetInternalNoficationsContactIds', Type__c = 'Information', Description__c = 'No of Ids ' + INCids.size());         insert (Ilg1);        return INCids;                //Case Owner        //Related User: Assigned Developer        //Related User: LastCaseComment_CreatedBy        //Case Team: Receive Internal Notifications        }                 static void MassDeleteInternalLogs()     {     	   List<InternalLog__c> lglist = new List<InternalLog__c>();           for (InternalLog__c l: [Select Id From InternalLog__c order by createddate asc limit 5])           {                 lglist.add(l);           }             InternalLog__c  Ilg1 = new InternalLog__c ( Section__c = 'StepstoneInternalCaseComment.MassDeleteInternalLogs', Type__c = 'Information', Description__c = 'No of Logs deleted : ' + lglist.size());           insert (Ilg1);                      delete (lglist);     }           //  mail.setHtmlBody('Your case:<b> ' + case.Id +' </b>has been created<p>'+    // ' View case <a href=https://na1.salesforce.com/'+case.Id+'>click here</a>');// Send the email you have created.//Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     
}