Search code examples
salesforceapex-code

How to send an email to an arbitrary address and merge in Lead values?


I need to send an email:

  • to an arbitrary email address
  • using an email template
  • merging in values from a Lead

The code would look something like this:

Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
msg.setToAddresses(new String[] { '[email protected]' });
msg.setSaveAsActivity(false);

// this causes a runtime error. Lead ID not allowed 
msg.setWhatId(lead.Id);

msg.setTemplateId(templateID);
messages.add(msg);

Problem is, you cannot use a Lead ID for the WhatID. I'm not sending an email to the Lead, so I can't use the Lead for the TargetObjectId.

Is this possible?


Solution

  • Frustrating that SFDC still doesn't support a more flexible templating context, isn't it? Given your constraints, I think you do have options:

    • do your own templating replacement by loading the template dynamically and replacing home-grown tags with lead fields (e.g. $LEAD.NAME or whatever)
    • temporarily save the Lead as a supported object (Account perhaps?), persist it, use that as the WhatId, send your email, and then rollback/delete (EDIT: as pointed out above, rollback apparently "unsends" emails, so don't use that.)
    • use a third-party or custom off-platform mail solution that offers template-based merging that is more flexible than Apex, probably via a WS API

    I've played with all of these approaches but the only one I've seriously implemented is #3. Option 1 seems like an attractive option assuming you can make it work.