+ Start a Discussion
Steve ThurstonSteve Thurston 

How to send an email using a template to a Contact, with information from a Lead

I am trying to use Apex to send an email to a Contact pulling information from a Lead.  The Contact I am trying to send the email to is a field on the Lead, so I can get their ID using SOQL easily enough.  But the problem seems to be a fundamental and baffling incompatability between the combination of using email templates, sent to a Contact, using information from a Lead.  Here is what methods I have found so far:

1) Messaging.SingleEmailMessage:  This is the email class I am using.

2) setTemplateID:  easy enough using SOQL query

3) setToAddresses:  You can't use this if you are using an email template

4) setTargetObjectId(targetObjectId):  Generally, this is who will receive the email.  In this case, it would be a Contact.  Unfortunately, this also sets the context for the email for the merge fields.  For the merge fields, I need the context to be the LEAD.  So "targetObjectId" would need to be the LEAD Id, but the email must not be sent to the Lead.

5)  setTreatTargetObjectAsRecipient(treatAsRecipient) = FALSE:   This gets around the above problem.  This means that if I set the Lead as the TargetObjectID, then it's email is NOT the recipient.  *So I need to define the recipient some other way.  This is where it all falls apart.*

6)  setWhatId(ID):  WhatId is used to set the email's context.  The context is the LEAD.  So I can't set this to the Contact ID.  Further, you can't use a Lead with setWhatID!

7)  ALSO:  singleMail.setSaveAsActivity(false);  I'm not sure if I need to worry about this or not.

So, since I can't use setToAddresses, and I can't use either setTargetObjectId or setWhatId to set the recipient, what the heck do I use?  Do I really have to give up using a template?  I've seen something about Visualforce email templates, but I don't understand what it's talking about.

The error I am getting when I try to send:  "Invalid entity type for whatId."

BTW, I cannot use a workflow.  A workflow sets up the follow-up email as a pending Task.  You can't convert the Lead until all pending tasks are removed.  However, none of this is being handled manually.  It's all being handled via a third party integration that I have no control over.  So what is happening is that the integration is trying to convert the Lead and it fails because there is a pending email notification that had been created by the workflow.  So instead of a workflow I am trying to schedule a daily email notification for all Leads that were created prior to today that have not been acted upon.