+ Start a Discussion
Reppin__505Reppin__505 

Apex Email Template Question

Hi, 

 

I have something of a minor issue using the send mail feature in Apex. I am trying to avoid having to hard code the email by using an email template instead. 

 

I would like this template to be sent to a Contacts email, and the template will use merge fields from a Lead record.

 

Now i'm using 'setTargetObject' as the lead record in which merge fields will be applied. And im using 'setToAddresses' as the email address of the contact in which to send the email to. 

 

What happens is that when the email template is sent to the Contact, it is also sent to the email address in the Lead record. I absolutely do not want the message going to the Lead.

 

So i've had to manually script the email in Apex to keep this from happening. 

 

Does anyone know a better way of handling this. Where i can use merge fields from the lead record to send an email template to an email address outside of the lead object?

Pratibh PrakashPratibh Prakash

Which type of email template your are using?

If you use visualforce email template then you can achieve the objective as:

 

Email Template:

 

<messaging:emailTemplate subject="Test" recipientType="Contact" relatedToType="Lead">
<messaging:plainTextEmailBody >
LEAD NAME: {!relatedTo.LastName}
</messaging:plainTextEmailBody>
</messaging:emailTemplate>

 

<messaging:emailTemplate subject="Test" recipientType="Contact" relatedToType="Lead"><messaging:plainTextEmailBody >LEAD NAME: {!relatedTo.LastName}</messaging:plainTextEmailBody></messaging:emailTemplate>

 

In Apex use setTargetObjectId() to set id of contact to set target email address and setWhatId() to set lead id.

 

Pradeep_NavatarPradeep_Navatar

Why are you using "setToAddresses" and "setTargetObject". Both are optional properties for a outbound messaging class simultanously. It's better to Use “setToAddresses”  and bind the email address with that property rather than “setTargetObject”.

Reppin__505Reppin__505

I'm not sure i follow. How can you bind say a contacts email address to the lead object for the merge fields in the email template?