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
LeeFrankeLeeFranke 

Using Email Template with Apex

I have a custom object (Eval_Forecast__c) and some email templates.

 

In a trigger, I would like to send an email using those templates populating the dynamic text of the template. I can get the email to send, but the problem is the dynamic text is not populated.

 

When I set the WhatId (which seems to be what I need to do), I get the error:

 

SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.

 

 

Here is the Apex code:

 

Messaging.SingleEmailMessage emailOut = new Messaging.SingleEmailMessage(); if(forecast.Stage__c =='Submitted to Sales Operations') { emailOut.setTemplateId('00XQ0000000QCUo'); } if(forecast.Stage__c =='Sales Order Released') { emailOut.setTemplateId('00XQ0000000QCV3'); } if(forecast.Stage__c =='Closed Cancelled') { emailOut.setTemplateId('00XQ0000000QCV8'); } emailOut.setTargetObjectId(user.Id);

 

Here is a sample of the template code:

 

*** Sales Order Has Been Released *** Eval Forecast Name: {!Eval_Forecast__c.Name} Account Name: {!Eval_Forecast__c.Account_name__c} Sales Order Number: {!Eval_Forecast__c.Sales_Order_Number__c} IMTR Number : {!Eval_Forecast__c.IMTR_Number__c} Note: Your Sales Order has been removed from shipping block and is now elidgible to ship.

 

 thanks,

 

lee

 

 

dawnzdydawnzdy

Hi ,

 

   Happened to read the guide now, it seems what id only works for contact and you were trying to send email to user.

 

    'Optional. If you specify a contact for the targetObjectId field, you can specify a whatId as well. '

 

    I haven't tried myself though. Hope it helps.

 

Dawn

khanWebgurukhanWebguru
blank_page

Dear All,

 

 I have an email template which is given below:

 

Evaluation Request from {!Lead.LastName} {!Lead.FirstName} for {!Lead.SupportProduct__c}, is pending and requires manual approval. <br/>

Click <a href="{!ApprovalRequest.Internal_URL}">here</a> to approve or reject this request.<br/><br/>

Thanks.

 

Whenever I use this template through "Approval Processes" it works fine. But I have different situation in which I cannot use "Approval Processes". For example I need that when a Lead create then email should be generate for Lead Approval and send to those receptionist that are belongs to selected region. If a lead belongs to ASIA then email should be send on asia@abc.com or if region is USA then it should be for usa@abc.com I successfully completd this task with static or just text base template. But whenever I use Customise template its not filling merge values. Following is TRIGER code:

 

trigger TestEmail on Lead (after insert)
{       
            MailerUtils.sendMail(Trigger.new[0].Region__c, String.valueOf(Trigger.new[0].Id), Trigger.new  [0].IsEmbargoe__c);


 

 

Now, following is MailerUtils class having sendMail method

 

public class MailerUtils
{
 
    public static void sendMail(string location, string leadId, Boolean IsEmbargoe)
    {
        string message;
        string temp = 'ApproveLeadTemplate';
        String[] toAddresses;
        List<Id> idsList = getEmailAddresses(location);
       
        if(IsEmbargoe == False)
        {
            temp = 'ApproveEmbargoeTemplate';
        }
        EmailTemplate e = [select Id,Name,Subject,body from EmailTemplate where name like :temp+'%'];
                                                  
        if(e != null || idsList==null)
        {
            Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.saveAsActivity = false;
   
            mail.setTargetObjectIds(idsList);
            mail.setTemplateId(e.Id);
           
            mail.setUseSignature(false);
            mail.setSaveAsActivity(false);


            // Send the email
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
          
        }
        else
        {
            Messaging.SingleEmailMessage mail1 = new Messaging.SingleEmailMessage();
            toAddresses = new String[] {'khan@abc.com'};
            mail1.setToAddresses(toAddresses);
            message = 'This email will recieve by you only if Template Not Found!!!';
            mail1.setHtmlBody(message);
        }
                
            }  
   
     public static List<Id> getEmailAddresses(string groupName)
     {

        List<String> idList = new List<String>();
       
        List<Id> mailToIds = new List<Id>();
       
        Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = :groupName];
       
        for (GroupMember gm : g.groupMembers) {
       
        idList.add(gm.userOrGroupId);
       
        }
       
        User[] usr = [SELECT Id, email FROM user WHERE id IN :idList];
       
        for(User u : usr) {
       
        mailToIds.add(u.Id);
       
        }
       
        return mailToIds;
       
    }
   

 

 

I have some public group having same name like ASIA, USA and Austrailia so that this help me to pull autmatic all user from selected group on the bases of Region.

 

But In all this I am having problem that the dynamic fields or u can say merge fields are not filling please help me in this context. Thanking in advance for you help.

 

Regards,

 

Asif Ahmed Khan

Sr. Software Eng.

Palmchip :)

kalai15kalai15

Do anyone got solution for this?? I'm also facing the same issue..

ERROR: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds

 

Im wondering that If i can't set the  "whatid" value for sending emails to users then how Merge fields shows up values in the email.... This is so weird....

 

I did 'Track Activities' enabled for the Custom object (the one i'm using).. and  'SaveAsActivity ' also 'false' but still facing the same issue...

 

Any help is highly appreciated...

 

ShoalShoal

You can't use the whatID when the targetObjectID is a user ID.