+ Start a Discussion
Prince VenkatPrince Venkat 

Emails based on picklistfield

Hi
when ever picklist value changes in contact whenever leadsource changes to web batch apex should send an email
whenever leadsource changes to Phone Inquiry another email should send based on the email filed of the records
(Should be done through batch apex As it is be scheduled)

Thanks in advance
 
Best Answer chosen by Prince Venkat
CharuDuttCharuDutt
Hii Prince 
Try Below Code
public class SendEmailToContacts implements Database.Batchable<sObject> {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT id,Email,LeadSource FROM Contact Where LastModifiedDate = today  ORDER By LastModifiedDate  DESC');
    }
    public void execute(Database.BatchableContext bc, List<Contact> records){
        list<String> Addresses = new list<String>();
        for(Contact Con : records){
            if(Con.LeadSource == 'Web' || Con.LeadSource == 'Phone Inquiry'){
                Addresses.add(Con.Email);
            }
        }
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

       mail.setToAddresses(Addresses);
        mail.setSubject('Test subject');
        mail.setPlainTextBody('Sample body');
       
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
    }
    public void finish(Database.BatchableContext bc){
        Id job = bc.getJobId();
    }
}

Test Class

@IsTest
public class SendEmailToContactsTest {
  @isTest    
    public static void testit() {
      
       list<Contact>lstCon = new  list<Contact>();
        list<Contact>lstConu = new  list<Contact>();
        for(integer i = 0;i<5;i++){
            Contact l = new Contact();
            l.LastName = 'name';
            l.Email ='test'+i+'@test.com';
            lstCon.Add(l);
        }

        insert lstCon;
        for(Contact con : lstCon){
            con.leadSource = 'web';
           lstConu.Add(Con);
        }
        update lstConu;
       
            SendEmailToContacts lp = new SendEmailToContacts();
        Id batchId = Database.executeBatch(lp);
    }

}



Please Mark It  As Best Answer If It Helps
Thank You!