So we have a trigger that automatically emails a Case Contact when a new Comment is added.
However for some users, we require that email to go to an alternate email address, NOT the one in the Contact's "Email" field.
How would this be done? How do you force Apex to use a particular email address, when also using a Visualforce Template?
thanks
Best Answer
Looking at an example I implemented some time back, when using SingleEmailMessage with a VF template, you must invoke
setTargetObjectId(targetObjId)
on the object of typeSingleEmailMessage
. AndtargetObjId
must be a Contact, Lead or User.setToAddresses(..)
, passing in a list of email addresses. Note that the SFDC Apex documentation is wrong here - it saysOptional. A list of email addresses to which you are sending the email. The maximum number of email addresses allowed is 100. This argument is allowed only when a template is not used.
This is not true, you can use with a template.targetObjId
is used by the VF template if needed to supply merge fields like Dear {!recipient.firstName}. In effect, as per the doc,targetObjId
references the standard controller for Contact, Lead, or User.{!recipient.xxx}
, then you can do what I ended up doing which was create a dummy Contactno-reply@mydomain.com
with corresponding email address and use that astargetObjId
. In your example, the real recipients were unconditionally set using thesetToAddresses(..)
method call on SingleEmailMessageNot a perfect solution but to the intended recipient, they will receive the email as if they were the intended recipient. The recipient is already conditioned to ignore the no-reply email address in the To: line
Here is my Util.sendTemplatedEmail method; you can adapt as needed; the caller is responsible for reserving the email message before invoking to avoid governor limits