Is it possible to have email sent with automatically user id inserted different that recipient user?
Firstly I have tried the following code
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses( Some_Beautiful_Custom_Setting__c.getInstance().recipients__c.split(' ') );
mail.setTemplateId( <Id of my template> );
mail.setTargetObjectId( <Id of user to be sent> );
mail.setSaveAsActivity( false );
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
having in my template something like {!User.Id}, but it inserts id of user under which I run this code, not the user I need. So I have tried to modify this code like following
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses( Some_Beautiful_Custom_Setting__c.getInstance().recipients__c.split(' ') );
mail.setTemplateId( <Id of my template> );
mail.setTargetObjectId( <Id of user to be sent> );
mail.setSaveAsActivity( false );
mail.setWhatId( u.Id );
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
but this even didn't work since it says that user Id cannot be applied as WhatId.
So, finally I decided to implement following solution
EmailTemplate et = [ Select Subject, HtmlValue From EmailTemplate where Id = <Id of my template> ];
for ( User u : usersToSendEmail ) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses( Some_Beautiful_Custom_Setting__c.getInstance().recipients__c.split(' ') );
mail.setSubject( et.Subject );
mail.setHtmlBody( et.HtmlValue.replace( '{!URL.getSalesforceBaseUrl()}', URL.getSalesforceBaseUrl().toExternalForm() ).replace( '{!User.Id}', u.Id ) );
}
but I don't really like it since it is not beautiful and Id is not set automatically but rather is replaced by code.
Does anyone know how can I make Salesforce automatically replace user Id in Email Template (which is different than user the code is running under and it is not constant so I can't hardcode it)?
Thanks.