function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Manjunath SC 5Manjunath SC 5 

how to send an automatic email when lead status is converted to "Qualified"

Hello all

I want to  send an automatic email when lead status is converted to "Qualified" , i tried it in workflow and process, it worked fine, now i want to try it in apex , i have ready made email template named "XXX" which shows as 

Hello {!Lead.LastName} 

Thank you for the registering with us 
Soon we will get back to you 

Team EduProserra

my apex class is

public class emailSending {

    public String Lead { get; set; }
    public string toMail { get; set;}
    public string ccMail { get; set;}
    public string repMail { get; set;}
    
    public void sendMail(){
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        string[] to = new string[] {toMail};
        string[] cc = new string[] {ccMail};
        
        email.setToAddresses(to);
        if(ccMail!=null && ccMail != '')
            email.setCcAddresses(cc);
        if(repmail!=null && repmail!= '')
            email.setInReplyTo(repMail);
        
        email.setSubject('Thank you for the Registration');
        
        email.setHtmlBody('Hello, {!Lead.LastName} <br/><br/>Thank you for Registration. <br/>We will get back to you for more details<br/><br/>Regards<br/> EduPro Team');
        try{
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        }catch(exception e){
            apexpages.addmessage(new apexpages.message(apexpages.severity.error,e.getMessage()));
        }
        
        toMail = '';
        ccMail = '';
        repMail = '';
    }
}

how do i design a trigger for this??
Khan AnasKhan Anas (Salesforce Developers) 
Hi Manjunath,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Trigger:
trigger SendEmailLead on Lead (after insert, after update) {
    
    for(Lead ld : trigger.new){
        if (ld.Status == 'Working - Contacted'){
            Helper_SendEmailLead.sendEmail(trigger.new);
        }
    }
}

Handler Class:
public class Helper_SendEmailLead {
    
    public static List<Lead> sendEmail(List<Lead> leads) {
        
        EmailTemplate et = [SELECT Id FROM EmailTemplate WHERE developername = 'Your_Template_Name' LIMIT 1];
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        
        for(Lead ld : leads){
            if(ld.Email != null){
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
                singleMail.setTargetObjectId(ld.Id);
                singleMail.setTemplateId(et.Id);
                singleMail.setSaveAsActivity(false);
                emails.add(singleMail); 
            }
        }
        Messaging.sendEmail(emails);
        
        return leads;
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Tad Aalgaard 3Tad Aalgaard 3
Khan, I think I see a flaw in your code.

In the code you posted you will be creating exponentially duplicate emails.  You are both iterating through the list of Leads and then calling the sendEmail method and also pushing through the entire list into the method where it's contents are iterated through a second time.

10 leads in the trigger could create 100 emails.
trigger SendEmailLead on Lead (after insert, after update) {
    
    for(Lead ld : trigger.new){
            Helper_SendEmailLead.sendEmail(trigger.new);
   }
}
Instead move the conditional out of the trigger and into the class and change this
if (ld.Email != null){
to this
if (ld.Status == 'Working - Contacted' && if(ld.Email != null){
Also, change the return type of the sendEmail method to void since there is no reason to return anything since the trigger will not be using any returned values.


 
Khan AnasKhan Anas (Salesforce Developers) 
True, my bad! Thank you, Tad, for pointing this out.

Here is the updated code:

Trigger:
trigger SendEmailLead on Lead (after insert, after update) {
    
    if(Trigger.isAfter) {
        Helper_SendEmailLead.sendEmail(trigger.new);
    }
}

Handler:
public class Helper_SendEmailLead {
    
    public static void sendEmail(List<Lead> leads) {
        
        EmailTemplate et = [SELECT Id FROM EmailTemplate WHERE developername = 'Your_Template_Name' LIMIT 1];
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        
        for(Lead ld : leads){
            if(ld.Email != null && ld.Status == 'Working - Contacted'){
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
                singleMail.setTargetObjectId(ld.Id);
                singleMail.setTemplateId(et.Id);
                singleMail.setSaveAsActivity(false);
                emails.add(singleMail); 
            }
        }
        Messaging.sendEmail(emails);
    }
}

Regards,
Khan Anas
Ajay K DubediAjay K Dubedi
Hi Manjunath,
Try this code:
Trigger:
trigger LeadTriggerSendMail on Lead (before insert, before update) {
    if((trigger.isInsert && trigger.isBefore) || (trigger.isUpdate && trigger.isBefore)) {
        LeadTriggerSendMail_handler.checkLeadStatus(trigger.new);
    }
}
Handler:
public class LeadTriggerSendMail_handler {
    public static void checkLeadStatus(List<Lead> leadList) {
        try {
            List<String> emailList = new List<String>();
            
            for(Lead l : leadList) {
                if(l.Email != null && l.Status == 'Qualified') {
                    emailList.add(l.Email);
                    EmailTemplate temp = [SELECT Id FROM EmailTemplate WHERE developername = 'XXX' LIMIT 1];
                    system.debug('emailList------' + emailList);
                    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                    if(emailList.size() > 0) {
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        mail.setToAddresses(emailList);
                        mail.setTemplateId(temp.Id);
                        mail.setTargetObjectId(l.Id);
                        mails.add(mail);
                    }
                    Messaging.sendEmail(mails);
                }
            }
        } catch (Exception ex) {
            system.debug('Exception---ofLine--->' + ex.getLineNumber());
            system.debug('Exception---Message--->' + ex.getMessage());
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi
Renuka SharmaRenuka Sharma
Thanks guys, 

i am trying do the same on the contact object now, in the contact object there is a custom checkbox field called "Course_completed__c" when i check the checkbox field, it should fire an email, i have designed a trigger and apex class, but i do get an error

Apex class - 

public class emailfeesurvey_handler {
    public static void checkfeesurvey(List<contact> contactlist) {
        try {
            List<String> emailList = new List<String>();
            
            for(contact c : contactList) {
                if(c.Email != null && c.checkbox == 'True') {
                    emailList.add(c.Email);
                    EmailTemplate temp = [SELECT Id FROM EmailTemplate WHERE developername = 'Course_complete_survey' LIMIT 100];
                    system.debug('emailList------' + emailList);
                    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                    if(emailList.size() > 0) {
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        mail.setToAddresses(emailList);
                        mail.setTemplateId(temp.Id);
                        mail.setTargetObjectId(c.Id);
                        mails.add(mail);
                    }
                    Messaging.sendEmail(mails);
                }
            }
        } catch (Exception ex) {
            system.debug('Exception---ofLine--->' + ex.getLineNumber());
            system.debug('Exception---Message--->' + ex.getMessage());
        }
    }
}


Trigger - 

trigger emailfeesurvey on Contact (before insert, before update) {
    if((trigger.isInsert && trigger.isBefore) || (trigger.isUpdate && trigger.isBefore)) {
        emailfeesurvey_handler.checkfeesurvey(trigger.new);
    }
}

the error i get is - Variable does not exist: checkbox and Method does not exist or incorrect signature: void checkfeesurvey(List<Contact>) from the type emailfeesurvey_handler

i know this is something to do with collections - should i take map instead list here
Somya TiwariSomya Tiwari

Hello,

I did tried this in my org !! You can also try this code !!
For the Trigger :

trigger MailTest on Lead (after insert, after update) {
        SendMailTest.send(trigger.new);
}
For the Helper Code :
public class SendMailTest{
    public static void send(List<Lead> lds) {
        EmailTemplate et = [SELECT Id FROM EmailTemplate WHERE developername = 'Your_Template_Name' LIMIT 1];
        List<Messaging.SingleEmailMessage> ems = new List<Messaging.SingleEmailMessage>();
  
        for(Lead ld : lds)
        {
            if(ld.Email != null && ld.Status == 'Working - Contacted')
            {
                Messaging.SingleEmailMessage sm = new Messaging.SingleEmailMessage();
                sm.setTargetObjectId(ld.Id);
                sm.setTemplateId(et.Id);
                sm.setSaveAsActivity(false);
                ems.add(sm); 
            }
        }
        Messaging.sendEmail(ems);
    }
}

 
Miledccs SmithMiledccs Smith
for me, this thread solution worked https://salesforce.stackexchange.com/questions/164931/is-there-a-way-to-call-javascript-after-action-on-visualforce-page
with regards
https://plex.software  (https://plex.softwarehttps://kodi.software/ https://luckypatcher.pro/
Ajay K DubediAjay K Dubedi
Hi Manjunath,
Here is the code for Contact, try this code:
 
public class emailfeesurvey_handler {
    public static void checkfeesurvey(List<Contact> contactList) {
        try {
            EmailTemplate temp = [SELECT Id FROM EmailTemplate WHERE developername = 'Course_complete_survey' LIMIT 1];
            Map<Id, String> emailMap = new Map<Id, String>();
            List<String> emailList = new List<String>();
            for(contact c : contactList) {
                if(c.Email != null && c.Check__c == True) {
                    emailMap.put(c.Id, c.Email);
                }
            }
            emailList = emailMap.values();
            system.debug('emailMap----' + emailMap.values());
            List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
            if(emailMap.size() > 0) {
                for(Contact c : contactList) {
                    if(emailMap.containsKey(c.Id) && emailList.contains(c.Email)) {
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        mail.setToAddresses(emailList);
                        mail.setTemplateId(temp.Id);
                        mail.setSubject('Testing');
                        String body = 'This mail is use for testing.';
                        mail.setHtmlBody(body);
                        mail.setTargetObjectId(c.Id);
                        mails.add(mail);
                    }
                }   
            }
            Messaging.sendEmail(mails);
        }
        catch (Exception ex) {
            system.debug('Exception---ofLine--->' + ex.getLineNumber());
            system.debug('Exception---Message--->' + ex.getMessage());
        }
    }
}

Thanks,
Ajay Dubedi
Manjunath SC 18Manjunath SC 18
Thank you very much everyone:)
Deepali KulshresthaDeepali Kulshrestha
Hi Manjunath,

It easy to send an email through apex code using a trigger. Please try the below code:-
 
Trigger ===>>>

trigger Trigger_send_Email_LeadConvert on Lead (after update){
    if(trigger.isAfter && trigger.isUpdate){
        Handler_send_Email_on_LeadConvert.sendEmail(Trigger.new);
    }
}


Handler Class===>

public class Handler_send_Email_on_LeadConvert {
    public static Boolean sendEmail(List<Lead> ldlist){
        try{
            Boolean sendSuccess  =  false;
            System.debug('lead List---->'+ldlist);
            Set<ID>   lID  =  new Set<ID>();
            if(ldlist != null){
                for(lead l : ldlist){
                    if(l.isConverted && l.Email != null){
                        lID.add(l.id);
                    }
                }
            }
            if(lid != null){
                List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                EmailTemplate templateid  = [Select id from Emailtemplate where Name =: 'XXX' Limit 1];
                System.debug('Email Template Id ---->'+templateid);
                if(templateid != null){
                    for(ID i : lID){
                        Messaging.SingleEmailMessage  mail = new Messaging.SingleEmailMessage();
                        mail.setTemplateId(templateid.Id);
                        mail.setTargetObjectId(i);
                        mail.setSenderDisplayName(userInfo.getUserName());
                        mails.add(mail);
                    }
                    system.debug('mails--------------->'+mails);
                    for (Messaging.SendEmailResult r: Messaging.sendEmail(mails)){
                        if (r.isSuccess()){
                            sendSuccess = true;
                        }
                    }
                }
            }
            
            return sendSuccess;
        }
        catch(Exception e){
            System.debug('Line No:-->'+e.getLineNumber()+'----->Error---->'+e.getMessage()+'----->Cause----->'+e.getCause());
            return false;
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com