+ Start a Discussion
sam_Adminsam_Admin 

Email sent via custom button doesn't show under Activity history on lead

We have a VF custom button on lead record that sends 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 );    
    
            try{             
                leadRecord = [select Status,ID,Contact__c,Name,Company,NumberOfEmployees,Street,City,State,PostalCode,Country,Website,Salutation,FirstName,
                             LastName,Title,Department__c,Email,Phone,MobilePhone,Fax,Product__c,Industry,Specialty__c,Rating,BuyingTimeframe__c,LeadSource,WebFormDetail__c,
                             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;
                    ReplaceTags();   
                }
            }
            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
                 try{
                    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));
    
                            mail.setTargetObjectId(c.id);
                            mail.setSubject(Subject);
                            mail.setHtmlBody(HtmlBody);
                            mail.setsaveAsActivity(true);                     
                        email.add(mail);
                        Messaging.sendEmail(email);
                        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Email sent successfully!'));
    
                        leadRecord.Status = 'Tracking';
                        update leadRecord;
                    }
                    else{
                        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 '';
            else 
                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">
    
            <br/>    
                <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}" /> 
        </apex:pageBlock>     
    </apex:form>
</apex:page>
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
{lease try in below manner


Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       <strong><em>Contact con=[select id from contact limit 1];        </em></strong>       
        String[] toAddresses = new String[] {recipient.Email};
        mail.setToAddresses(toAddresses);
        mail.setBccSender(true);
        String[] bccAddresses = new String[] {person.Email};
        mail.setBccAddresses(bccAddresses);
       mail.setTargetObjectId(con.id);
        mail.setSaveAsActivity(true);
        mail.setSubject(subject);
        mail.setPlainTextBody(templateBody);
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
Regards
Ashish
 
sam_Adminsam_Admin
I get an error Error: Compile Error: expecting right curly bracket, found '<' at line 147 column 21
sam_Adminsam_Admin
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                     <strong><em>Contact con=[select id from contact limit 1];        </em></strong>       
        String[] toAddresses = new String[] {recipient.Email};
        mail.setToAddresses(toAddresses);
        mail.setBccSender(true);
        String[] bccAddresses = new String[] {person.Email};
        mail.setBccAddresses(bccAddresses);
       mail.setTargetObjectId(con.id);
        mail.setSaveAsActivity(true);
        mail.setSubject(subject);
        mail.setPlainTextBody(templateBody);
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});   
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        Contact con=[select id from contact limit 1];        
        String[] toAddresses = new String[] {recipient.Email};
        mail.setToAddresses(toAddresses);
        mail.setBccSender(true);
        String[] bccAddresses = new String[] {person.Email};
        mail.setBccAddresses(bccAddresses);
       mail.setTargetObjectId(con.id);
        mail.setSaveAsActivity(true);
        mail.setSubject(subject);
        mail.setPlainTextBody(templateBody);
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

try this one .
sam_Adminsam_Admin
How do we remove the {recipient.Email}? it says Variable does not exist: recipient.Email, in my case the recipient can be anyone, i can go to amy lead and based on contry the recipient always changes
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        Contact con=[select id from contact limit 1];        
        List<String> toAddresses = new List<String>;
		//YOUR EMAIL ADDRESS
		toAddresses.add('test@GMAIL.COM');
        mail.setToAddresses(toAddresses);
        mail.setBccSender(true);
        String[] bccAddresses = new String[] {person.Email};
        mail.setBccAddresses(bccAddresses);
       mail.setTargetObjectId(con.id);
        mail.setSaveAsActivity(true);
        mail.setSubject(subject);
        mail.setPlainTextBody(templateBody);
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

try above code to add any email.

Regards
Ashish
ashish.sharma.devsfdc@gmail.com
sam_Adminsam_Admin
Sorry it's not sending email but i just altered my code it works but just one issue, the email is being sent but it's sending email to the email address on lead record, it's not sending to the person i select from button, if this gets fixed then my issue is solved, any idea? here is my code

 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));
                        
                        mail.setTargetObjectId(c.id);
                        mail.setSubject(Subject);
                        mail.setHtmlBody(HtmlBody); 
                        mail.setsaveAsActivity(true); 
                        mail.setTargetObjectId(LeadRecord.Id);                                     
                    email.add(mail);
                    Messaging.sendEmail(email);                      
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Email sent successfully!'));
sam_Adminsam_Admin
If i use this code it says unexpected token: ';' at List<String> toAddresses = new List<String>;
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Sorry ,i missed to lissed inilization syntax.
 
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        Contact con=[select id from contact limit 1];        
        List<String> toAddresses = new List<String>();
		//YOUR EMAIL ADDRESS
		toAddresses.add('test@GMAIL.COM');
        mail.setToAddresses(toAddresses);
        mail.setBccSender(true);
        String[] bccAddresses = new String[] {person.Email};
        mail.setBccAddresses(bccAddresses);
       mail.setTargetObjectId(con.id);
        mail.setSaveAsActivity(true);
        mail.setSubject(subject);
        mail.setPlainTextBody(templateBody);
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

Regards
Ashish
ashish.sharma.devsfdc@gmail.com
sam_Adminsam_Admin
it doesn't works, not saving as activity