+ Start a Discussion

SingleEmailMessage using setTemplateId NEED URGENT HELP

Hello Everyone,

I hope you can help me on this..Im working with singleEmail to send an email to a particular sales representative on every territory. but every time I invoked my trigger via update of my objects, it returns an exception. The error is: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.\.: Trigger.Notify_Rep_Trigger: line 90, column 21

my code is written below:

Account territory = [select Territory_Name__c from Account where Id =:data.Account_ID__c];
            if(territory.Territory_Name__c != null)
                List<string> splitID = territory.Territory_Name__c.split(';', -1);
                Set<string> tID = new Set<string>();
                List<Territory> territoryId = [Select id From Territory where name in :splitID];
                List<UserTerritory> usersId = [Select UserId From UserTerritory where territoryid in :territoryId];
                for(integer x=0; x < usersId.size(); x++)
                List<User> emailAdd = [select Id, email from User where Id in :tID];
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                List <String> Addresses = new List<String>();
                for(integer i=0; i < emailAdd.size(); i++)
                    //String[] toAddresses = new String[] {emailAdd[i].email};
                    String toTargetObjects = (string)emailAdd[i].Id;
                    system.debug('target object deb:'+toTargetObjects);
                    system.debug('data id deb:'+data.Id);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

any suggestion? I would really appreciate it if you can help me on this.

Thanks in advance,


Message Edited by wilson34 on 11-21-2008 01:50 AM

Message Edited by wilson34 on 11-21-2008 01:51 AM

Message Edited by wilson34 on 11-21-2008 01:51 AM

Message Edited by wilson34 on 11-21-2008 01:53 AM
by the way, In addition to what Ive asked earlier, should I set the templateId to ID datatype?

try this:mail.setSaveAsActivity(false)
Rasmus MenckeRasmus Mencke

what type of email template are you using?


For regular email templates you can not use the WhatId


If you use Visualforce email templates you can use whatId's even when sending to users





setWhatId doesn't work even with VF template.

hello guys,


I really appreciate all your posts.  I think Mak is correct with the setWhatId. Everytime I use that with the template, my code produces an error. 

kevin hekevin he



I think you use setWhatId in a wrong way.If you specify a contact for the targetObjectId field, you can specify a whatId as well. That also means only when you setTargetObjectId using a contactId, you can use setWhatId and you can get merge fileds from email template.

Does anyone know how this can be done with a trigger.  I need to send an email to a user and I need the email to show up as a task on an Asset (whatID).  Except I keep getting an error: WhatId is not available for sending emails to UserIds.  Why?



I am running the following code


public List<UserTerritory> getUsers1(){
        List<UserTerritory> uid=[Select UserId From UserTerritory where TerritoryId=:ApexPages.currentPage().getParameters().get('id')];
        return uid;


I am getting the following error


Error: Compile Error: Incompatible types since an instance of LIST:SOBJECT:UserTerritory is never an instance of LIST:userterritory at line 9 column 33 


line 9 is List<UserTerritory> uid=[Select UserId From UserTerritory where TerritoryId=:ApexPages.currentPage().getParameters().get('id')];


Please tell me where i am going wrong. Please reply as soon as possible . I am stuck on this from a very long time. Its really urgent.


Thanks in advance




I'm having a problem setting the TargetObjectId to a userid.  I have a VF email template that I would like to send to my Lead Owner.  I set the targetObjectId to a userid and it fails with a "Messaging.SendEmailError[getTargetObjectId=null;]".


Here I set up the email:


Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.settargetObjectId('005T0000000gNPn');

 Just before I send it, I read back the contents, then send and read the results:


20091128203118.430:Class.Lead_Utils.ProcessOwnership: line 139, column 4: Sending out emails: (Messaging.SingleEmailMessage[getBccAddresses=null;getCcAddresses=null;getCharset=null;getDocumentAttachments=null;getFileAttachments=null;getHtmlBody=null;getOrgWideEmailAddressId=null;getPlainTextBody=null;getTargetObjectId=005T0000000gNPnIAM;getTemplateId=00XT0000000eyFdMAI;getToAddresses=null;getWhatId=null;isUserMail=false;])

20091128203118.430:Class.Lead_Utils.ProcessOwnership: line 141, column 4: Results of email send: (Messaging.SendEmailResult[getErrors=(Messaging.SendEmailError[getTargetObjectId=null;]);isSuccess=false;])

 It shows the userid I populated as the "getTargetObjectId" but then fails to send. 


If I run this very same test with a Lead Id as the TargetObjectId, all is good.


20091128203305.107:Class.Lead_Utils.ProcessOwnership: line 139, column 4: Sending out emails: (Messaging.SingleEmailMessage[getBccAddresses=null;getCcAddresses=null;getCharset=null;getDocumentAttachments=null;getFileAttachments=null;getHtmlBody=null;getOrgWideEmailAddressId=null;getPlainTextBody=null;getTargetObjectId=00QT0000005cbFaMAI;getTemplateId=00XT0000000eyFdMAI;getToAddresses=null;getWhatId=null;isUserMail=false;])

20091128203305.107:Class.Lead_Utils.ProcessOwnership: line 140, column 42: Single email queued for send (pending commit) : subject: New Lead Created test, bccSender: false, saveAsActivity: true, useSignature: true, targetObjectId: 00QT0000005cbFaMAI, templateId: 00XT0000000eyFdMAI, plainTextBody: Hello , charset: ISO-8859-1,

20091128203305.107:Class.Lead_Utils.ProcessOwnership: line 141, column 4: Results of email send: (Messaging.SendEmailResult[getErrors=();isSuccess=true;])


 Is there something about the fact that I'm sending an email template to a User that is causing issues?  I noticed that the isUserMail property is false - although I can't find any documentation on this it seems to make sense that it would be true if the email was being sent to a User.


Note that I am in Sandbox in case that makes a difference.


Thanks for any assistance you can give.








Figured it out - SaveAsActivity must be explicitly set to False when you are using a User as a TargetObjectId.
Make sure that you have the "Allow Activities" enabled on the sobject for whatever you are passing in your WhatId.

Here it is two and a half years later and this problem continues to bite salesforce developers.   For example, I wanted a simple schedule task that runs and sends messages to Opportunity owners, that their opportunities will be auto closed by another task in X days.   Ideally, I should just need to set the Template Id, TargetOtherId, and WhatId values.   With a SaveAsActivity value of true, I should be good to go.


But intead if TargetOtherId is a User Id, then you can't set WhatId.  So I have to add code to query the template and do all the variable substitution manually.  In addition, since WhatId cannot be set, neither can SaveAsActivity be used, so the Task to add the notification to the Opportunity ActivityHistory is also a manual process.  To makes matter worse, there is no way to backout an single e-mail in a batch.   So if you queue the message first, but fail in creating the task then you have to roll back the whole batch.   If on the otherhand you create the task first and then the e-mail fails, you then have to delete the tasks and hope the delete does not fail.


Aggg.   What a mess.



Okay so I finally solved this.  So use setTargetObjectId() and point it to ANY contact (they will get emailed).  Then just add your email addresses with setToAddresses(), this will then let you use setWhatId() without complaint.


What a mess!  I get really wound up when Salesforce insist on having Contact references where they are often not required.


In my use case I have created an audit object to store events generated in Apex code.  When one of these is created I want to send an email to the dev team.


Thanks to Auteyus I've managed this by creating a dummy contact: **-system-contact.


The use of templates in Apex should most certainly not require this level of workaround.