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
lopezclopezc 

setTargetObjectId not working

I have a problem regarding salesforce email under apex area.

The problem is using 'Html Email Templates' with setTargetObjectId method does not set the User Id:

 

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); logger.log('User found: ' + caseR.User__c); mail.setTargetObjectId(caseR.User__c); mail.setTemplateId('00XT0000000iwz7'); Messaging.Sendemailresult[] emailResult = Messaging.sendEmail(new Messaging.Email[] { mail } , false); logger.log('Email Result: ' + emailResult);

 

And the logging result says that TargetObjectId is null. Why?:

 

2/01/2010 09:15: User found: 00520000000pjkYAAQ 12/01/2010 09:15: Email Result: (Messaging.SendEmailResult[getErrors=(Messaging.SendEmailError[getTargetObjectId=null;]);isSuccess=false;])

 

Please help!

 

thanks,

Cristina.

lopezclopezc

I changed the ID to be a Lead Id and it worked. Does it means we can't use User Ids? In the documentation I found it is possible:

 

setTargetObjectId:

Optional. The ID of the contact, lead, or user

to which the email will be sent. The ID you

specify sets the context and ensures that merge

fields in the template contain the correct data.

Do not specify the IDs of records that have the

Email Opt Out option selected.

All email must have a recipient value of at least

one of the following:

toAddresses

ccAddresses

bccAddresses

targetObjectId

targetObjectIds

ag_nameag_name

Hello Everyone,

 

Any workaround about this? mail.setTargetObjectId is not working for users but as per the documentation it is included.

 

Thanks in advance

SathyaincampusSathyaincampus

Hi,

 

   did you get an answer for this? I am having the same problem now. can you please help by letting me know how you solved this issue?

 

Regards

Sathya

rpp0910rpp0910

Same problem here . where you able to find out any solution ?

BW Developer DaveBW Developer Dave

I was having the same issue. This code below works. NOTE: The var named userId is retrieved from a custom setting but you can get it from anywhere.

 

List<Messaging.SingleEmailMessage> msgs = new List<Messaging.SingleEmailMessage>();

Messaging.SingleEmailMessage m = new Messaging.SingleEmailMessage();
// This is important!
m.setSaveAsActivity(false);
m.setTargetObjectId(userId);
m.setSubject('TEST FROM SF!!');
m.setPlainTextBody('This is a test!');

msgs.add(m);
Messaging.sendEmail(msgs);

 

Please note the setSaveAsActivity method and I am passing false. This is important as this did not work until I added that. Let me know if you have any questions.