+ Start a Discussion
SV MSV M 

Unable to use Contact Owner Email

Hi, I have a batch class which should send email to contact owner which includes contacts created from lead conversion. I was unable to use contact owner email in ToAddress field. Here is my batch class..

//Batch Class

global class EmailWithAttachment implements Database.Batchable <sObject>, Database.Stateful{
    public List<Contact> conList {get;set;}
    public String body{get;set;}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, FirstName, LastName, LeadSource, ConvertedDate isConverted FROM Lead';
        //system.debug('aaaaaaa'+query);
        return Database.getQueryLocator(query);
        
    }
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        List<Contact> conList = new List<Contact>();
        for(Lead lead : scope) {
            conList = ([SELECT FirstName, LastName, Email, Phone
                        FROM Contact 
                        WHERE Id IN (SELECT ConvertedContactId FROM Lead)]);
        }
        system.debug('Contacts List'+conList);
        String.join(conList,',');
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        body = 'Contact Details : ' +conList+ '';
        email.setPlainTextBody(body);
        email.setSubject('Contact Details from Converted Lead');
        email.setToAddresses(new string[]{'maddulasaivineeth@gmail.com'});
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        //system.debug('Contacts'+conList);
    }
    global void Finish(Database.BatchableContext BC) {
        
    }

Can someone please help me write a test class for the same.

Thanks in Advance...
Best Answer chosen by SV M
PRAKASH JADA 13PRAKASH JADA 13
Hi,


Here is the solution to your problem with test class and with 100% code coverage

Batch class:
----------------------------------------------------------
global class EmailWithAttachment implements Database.Batchable <sObject>, Database.Stateful{
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, FirstName, LastName, LeadSource, ConvertedDate, ConvertedContactId, isConverted FROM Lead';
        //system.debug('aaaaaaa'+query);
        return Database.getQueryLocator(query);
        
    }
    
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        Set<Id> convertedIdSet = new Set<Id>();
        List<messaging.SingleEmailMessage>  emails = new List<messaging.SingleEmailMessage>();
        
        for(Lead lead : scope) {
            convertedIdSet.add(lead.ConvertedContactId);
        }// END FOR
        
        if(convertedIdSet != null && convertedIdSet.size() > 0) {
            List<String> ownerEmails = EmailWithAttachment.getUserEmails(convertedIdSet);
            
            for(String ownerEmail : ownerEmails) {
                
                system.debug('Contact Owner Email : ' +ownerEmail);
                messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
                String body = 'Contact Details : ' +ownerEmail+ ',';
                email.setPlainTextBody(body);
                email.setSubject('Contact Details from Converted Lead');
                email.setToAddresses(new string[]{ownerEmail});
                emails.add(email);
                
            }// END FOR
            
            Messaging.SendEmailResult[] results = Messaging.sendEmail(emails);
            if (results[0].success) {
                System.debug('The email was sent successfully.');
            } else {
                System.debug('The email failed to send: '
                             + results[0].errors[0].message);
            }
            //system.debug('Contacts'+conList);
            
        }
    }
    
    global void Finish(Database.BatchableContext BC) {
        Database.executeBatch(new EmailWithAttachment(), 200); // Additing for test class
    }
    
    //== Method to get the user emails
    private static List<String> getUserEmails(Set<Id> convertedIdSet) {
        Set<Id> ownerIds     = new Set<Id>();
        List<String> emails     = new List<String>();
        
        // Query to fetch the List of contact
        List<Contact> conList = [SELECT FirstName, LastName, Email, Phone, OwnerId 
                                 FROM Contact 
                                 WHERE Id =: convertedIdSet];
        
        // Condition to check to the contact query results
        if(conList != null && conList.size() > 0) {
            
            // Loop to iterate over the List of Contacts
            for(Contact con : conList) {
                ownerIds.add(con.OwnerId);
            }// END FOR
            
            List<User> users = [SELECT ID, Name, Email FROM User WHERE Id =:ownerIds];
            
            // Condition to check for the User List
            if(users != null && users.size() > 0) {
                for(User user : users) {
                    emails.add(user.Email);
                }// END FOR
            }// END IF
        }// MAIN IF ENDS  
        return emails;
    }
}


Test class:
---------------------------------------------
@isTest
public class EmailWithAttachmentTest {
    @testSetUp static void prepareTestData() {
        // create Lead
        Lead lead = EmailWithAttachmentTest.createLead();
        insert lead;
        
    }
    
    // Test Method to execute the Batch class
    @isTest static void testLeadConvert() {
        Lead newLead             = [SELECT Id, FirstName, LastName FROM Lead LIMIT 1];
        database.leadConvert lc = new database.leadConvert();
        lc.setLeadId(newLead.id);
        
        leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        
        Contact contact = [SELECT ID, OwnerId FROM Contact WHERE ID IN (SELECT ConvertedContactId FROM Lead)];
        System.assert(contact != null);
        
        Database.executeBatch(new EmailWithAttachment(), 200);
    }
    
    //== Create Lead
    private static Lead createLead() {
        lead newLead         = new lead() ;
        newLead.FirstName     = 'Test';
        newLead.LastName     = 'Lead';
        newLead.Company     = 'TestCompany';
        newLead.Status         = 'contacted';
        newLead.Email         = 'maddulasaivineeth@gmail.com';
        return newLead;
    }
}


I hope this helps. 

Thanks,
Prakash. J

All Answers

PRAKASH JADA 13PRAKASH JADA 13
Hi,


Here is the solution to your problem with test class and with 100% code coverage

Batch class:
----------------------------------------------------------
global class EmailWithAttachment implements Database.Batchable <sObject>, Database.Stateful{
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, FirstName, LastName, LeadSource, ConvertedDate, ConvertedContactId, isConverted FROM Lead';
        //system.debug('aaaaaaa'+query);
        return Database.getQueryLocator(query);
        
    }
    
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        Set<Id> convertedIdSet = new Set<Id>();
        List<messaging.SingleEmailMessage>  emails = new List<messaging.SingleEmailMessage>();
        
        for(Lead lead : scope) {
            convertedIdSet.add(lead.ConvertedContactId);
        }// END FOR
        
        if(convertedIdSet != null && convertedIdSet.size() > 0) {
            List<String> ownerEmails = EmailWithAttachment.getUserEmails(convertedIdSet);
            
            for(String ownerEmail : ownerEmails) {
                
                system.debug('Contact Owner Email : ' +ownerEmail);
                messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
                String body = 'Contact Details : ' +ownerEmail+ ',';
                email.setPlainTextBody(body);
                email.setSubject('Contact Details from Converted Lead');
                email.setToAddresses(new string[]{ownerEmail});
                emails.add(email);
                
            }// END FOR
            
            Messaging.SendEmailResult[] results = Messaging.sendEmail(emails);
            if (results[0].success) {
                System.debug('The email was sent successfully.');
            } else {
                System.debug('The email failed to send: '
                             + results[0].errors[0].message);
            }
            //system.debug('Contacts'+conList);
            
        }
    }
    
    global void Finish(Database.BatchableContext BC) {
        Database.executeBatch(new EmailWithAttachment(), 200); // Additing for test class
    }
    
    //== Method to get the user emails
    private static List<String> getUserEmails(Set<Id> convertedIdSet) {
        Set<Id> ownerIds     = new Set<Id>();
        List<String> emails     = new List<String>();
        
        // Query to fetch the List of contact
        List<Contact> conList = [SELECT FirstName, LastName, Email, Phone, OwnerId 
                                 FROM Contact 
                                 WHERE Id =: convertedIdSet];
        
        // Condition to check to the contact query results
        if(conList != null && conList.size() > 0) {
            
            // Loop to iterate over the List of Contacts
            for(Contact con : conList) {
                ownerIds.add(con.OwnerId);
            }// END FOR
            
            List<User> users = [SELECT ID, Name, Email FROM User WHERE Id =:ownerIds];
            
            // Condition to check for the User List
            if(users != null && users.size() > 0) {
                for(User user : users) {
                    emails.add(user.Email);
                }// END FOR
            }// END IF
        }// MAIN IF ENDS  
        return emails;
    }
}


Test class:
---------------------------------------------
@isTest
public class EmailWithAttachmentTest {
    @testSetUp static void prepareTestData() {
        // create Lead
        Lead lead = EmailWithAttachmentTest.createLead();
        insert lead;
        
    }
    
    // Test Method to execute the Batch class
    @isTest static void testLeadConvert() {
        Lead newLead             = [SELECT Id, FirstName, LastName FROM Lead LIMIT 1];
        database.leadConvert lc = new database.leadConvert();
        lc.setLeadId(newLead.id);
        
        leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        
        Contact contact = [SELECT ID, OwnerId FROM Contact WHERE ID IN (SELECT ConvertedContactId FROM Lead)];
        System.assert(contact != null);
        
        Database.executeBatch(new EmailWithAttachment(), 200);
    }
    
    //== Create Lead
    private static Lead createLead() {
        lead newLead         = new lead() ;
        newLead.FirstName     = 'Test';
        newLead.LastName     = 'Lead';
        newLead.Company     = 'TestCompany';
        newLead.Status         = 'contacted';
        newLead.Email         = 'maddulasaivineeth@gmail.com';
        return newLead;
    }
}


I hope this helps. 

Thanks,
Prakash. J
This was selected as the best answer
SV MSV M
The code worked perfect. Thanks for your help...