We have a VF custom button on lead record that sends details of lead via email to a selected contact but when the email is sent it doesn't shows up on lead activity history, is there any way to track the emails being sent through this button?

Apex class

/*Controller to send This lead to any selected Contact */

public class EmailController {
    public Lead leadRecord {get;set;}   
    public String TemplateID {get;set;}
    public String subject { get; set; }
    public String body { get; set; }
    public String htmlBody { get; set; }          
    public EmailTemplate  ET{ get; set; }
    public EmailController(ApexPages.StandardController controller) {
        String lid = '';
        TemplateID = ''; 
        htmlBody ='';
        if(ApexPages.currentPage().getParameters().get('id') != null )
            lid = ApexPages.currentPage().getParameters().get('id');
         system.debug('lidid ' + lid );    

            leadRecord = [select Status,ID,Contact__c,Name,Company,NumberOfEmployees,Street,City,State,PostalCode,Country,Website,Salutation,FirstName,
                         Description,Marketing_Comments__c from Lead where id = : lid];
            //Change the Template name below.
            ET = [Select ID,HTMLValue,Subject from EmailTemplate  where   name = 'Lead Email' ];            
            if (ET != null){
                TemplateID  = ET.id;        
                htmlBody  = ET.HTMLValue ;
                Subject = ET.Subject;
        catch(Exception e){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,e.getMessage()));

    public void ReplaceTags(){

        if(htmlBody.indexOf('{!Lead.Id}') >-1)
            htmlBody = htmlBody.replace('{!Lead.Id}',nullToString(leadRecord.Id));

        if(htmlBody.indexOf('{!Lead.Name}') >-1)
            htmlBody = htmlBody.replace('{!Lead.Name}',nullToString(leadRecord.Name));

        if(htmlBody.indexOf('{!Lead.Company}') >-1)
            htmlBody = htmlBody.replace('{!Lead.Company}',nullToString(leadRecord.Company));

        if(htmlBody.indexOf('{!Lead.NumberOfEmployees}') >-1)
            htmlBody = htmlBody.replace('{!Lead.NumberOfEmployees}',nullToString(String.valueOf(leadRecord.NumberOfEmployees)));

        if(htmlBody.indexOf('{!Lead.Address}') >-1){
            String Address = '' ;
            Address =  Address  + nullToString(String.valueOf(leadRecord.Street));
            Address =  Address  + ' ' + nullToString(leadRecord.City);
            Address =  Address  + ','+ nullToString(leadRecord.State);
            Address =  Address  + ' ' + nullToString(leadRecord.PostalCode);
            Address =  Address  + ' ' + nullToString(leadRecord.Country);
            htmlBody = htmlBody.replace('{!Lead.Address}',Address);

        if(htmlBody.indexOf('{!Lead.Street}') >-1)
            htmlBody = htmlBody.replace('{!Lead.Street}',nullToString(String.valueOf(leadRecord.Street)));

        if(htmlBody.indexOf('{!Lead.City}') >-1)
            htmlBody = htmlBody.replace('{!Lead.City}',nullToString(leadRecord.City));

        if(htmlBody.indexOf('{!Lead.State}') >-1)
            htmlBody = htmlBody.replace('{!Lead.State}',nullToString(leadRecord.State));

        if(htmlBody.indexOf('{!Lead.PostalCode}') >-1)
           htmlBody = htmlBody.replace('{!Lead.PostalCode}',nullToString(leadRecord.PostalCode));

        if(htmlBody.indexOf('{!Lead.Country}') >-1)
            htmlBody = htmlBody.replace('{!Lead.Country}',nullToString(leadRecord.Country));

        if(htmlBody.indexOf('{!Lead.FirstName} ') >-1)
            htmlBody = htmlBody.replace('{!Lead.FirstName} ',nullToString(leadRecord.FirstName) );

        if(htmlBody.indexOf('{!Lead.LastName}') >-1)
            htmlBody = htmlBody.replace('{!Lead.LastName}',nullToString(leadRecord.LastName));

        if(htmlBody.indexOf('{!Lead.Title}') >-1)
            htmlBody = htmlBody.replace('{!Lead.Title}',nullToString(leadRecord.Title));

    public PageReference send() {
     List<Messaging.SingleEmailMessage> email = new List<Messaging.SingleEmailMessage>();

        if(leadRecord.Contact__c == null){
             ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Please select contact and Try again.'));
             return null;   

        if (TemplateID != null){
            // Query Contact Email ID
                Contact c =  [Select Id,Email,Name from Contact where ID =: leadRecord.Contact__c]; 
                if (c.Email != null && c.Email != ''){ 
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

                        if(htmlBody.indexOf('{!Contact.Name}') >-1)
                            htmlBody = htmlBody.replace('{!Contact.Name}',nullToString(c.name));
                       String[] toAddresses = new String[] {c.email};
                    //  mail.setTargetObjectId(LeadRecord.Id);                    
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Email sent successfully!'));

                    leadRecord.Status = 'Tracking';
                    update leadRecord;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Selected Contact has no Valid Email Address, kindly update the contact and Try again.'));
                    return null;   
             }catch(Exception e){}

        return new PageReference('/' + leadRecord.id);  
    public String nullToString(String s){
        if (s== null)
            return '';
            return s;           
    public PageReference cancel(){
        return new PageReference('/' + leadRecord.id);  

VF Page:

<apex:page standardcontroller="Lead" extensions="EmailController" showheader="false">
    <apex:form >
        <apex:pageBlock title="Please select the Contact below">

                <apex:pageMessages />
                <b><apex:outputLabel value="To" for="To"/>:</b><br /> 
                <apex:inputField value="{!leadRecord.Contact__c}" id="To" />
                <br />
                <br />                                
                <b><apex:outputLabel value="Subject" for="Subject"/>:</b><br />     
                <apex:outputText value="{!ET.subject}" id="Subject" />
                <br />
                <br />               
                <apex:inputTextArea value="{!htmlBody}" id="Body"  rows="30" cols="80" richText="true" disabled="true" /> 
                <br /><br /><br />
                <apex:commandButton value="Send Email" action="{!send}" />
                <apex:commandButton value="Cancel & Return" action="{!Cancel}" /> 
  • If i comment the line // mail.setTargetObjectId(LeadRecord.Id); then the email is being sent to the contact i choose on lead record but it doesn't shows in activity history, if i don't comment it then it sends email to the email address on lead and it also tracks under activity history, not sure why it doesn't track when iam sending it to contact, something wrong
    – Admin_BA
    Commented Jun 6, 2016 at 22:33
  • Please check my updated answer.
    – Saroj Bera
    Commented Jun 8, 2016 at 13:07
  • @Admin_BA Glad to now it work for you. Now you can award the bounty. Commented Jun 10, 2016 at 18:00

2 Answers 2


you need to use saveAsActivity to add this as activity.


This is the missing key here.

Update: Use the leadId in targetObject Id to add in the Activity under lead and set the contact email address in to address to send email to contact.

String[] toAddresses = new String[] {usr.email};

And in the end set the mail.setTreatTargetObjectAsRecipient(false); so that your lead email will not get email.

Complete email code for reference

String[] toAddresses = new String[] {c.email};
  • Where exactly do i add it? if i add it below mail.setHtmlBody(HtmlBody); then it's throwing me an error
    – Admin_BA
    Commented Jun 3, 2016 at 17:40
  • You can add just after this mail.setHtmlBody(HtmlBody); line.
    – Saroj Bera
    Commented Jun 3, 2016 at 17:48
  • @SarojBera so i added mail.setsaveAsActivity(true); but when i send email it still doesn't shows under lead activity history, any idea?
    – Admin_BA
    Commented Jun 3, 2016 at 17:59
  • As I mentioned in my answer that you have to supply "what id" as well along with setSaveAsActivity .
    – Saroj Bera
    Commented Jun 3, 2016 at 18:04
  • 1
    @TusharSharma Iam getting error when i use mail.setTargetObjectId(lead.Id); Method does not exist or incorrect signature: [Messaging.SingleEmailMessage].setTargetObjectId(Schema.SObjectField)
    – Admin_BA
    Commented Jun 3, 2016 at 20:04

You have to set setSaveAsActivity and setWhatId.


In your code, you have set TargetObjectId twice as mail.setTargetObjectId(c.id); and mail.setTargetObjectId(LeadRecord.Id);. Thats why when you comment mail.setTargetObjectId(LeadRecord.Id); it is sent to Contact.

I was going through your code and I believe your Lead does not have email address and you are not logging the exception catch(Exception e){} anywhere. Can you

please update this line

catch(Exception e){}

with this new line

catch(Exception e){System.debug('The following exception has occurred: ' + e.getMessage());}

and see what is the error message in debug log.

  • the lead does has email address and it's being sent to that email address and logging an activity but don't need to send this to lead, i need to send it to contact and should be able to log an activity
    – Admin_BA
    Commented Jun 8, 2016 at 22:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .