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
SV MSV M 

Send email with contact details created by lead conversion

Hi, I have written a batch class where I would like to send an email to contact owner with the contact details created by lead conversion.

//Batch Class
global class LeadConversionEmail implements Database.Batchable <sObject>, Database.Stateful{
    //public List<Contact> conList {get;set;}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, LeadSource, ConvertedDate FROM Lead WHERE ConvertedContactId != NULL';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        List<Contact> conList = new List<Contact>();
        for(Lead ld : scope) {
            conList.add([SELECT FirstName, LastName 
                         FROM Contact 
                         WHERE Id IN (SELECT ConvertedContactId FROM Lead)]);
        }
    }
    global void Finish(Database.BatchableContext BC) {
       messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String body = 'FirstName ' +conList.FirstName+ 'LastName ' +conList.LastName+ 'done'; 
    }
}

I am getting errors at body saying Variable does not exist. Can you help me resolve the problem and how to send email to contact owner.

Thanks in Advance.
sachinarorasfsachinarorasf
Hi Sai Vineeth Maddula,

Here is the updated Apex Code Which is working fine.


global class LeadConversionEmail implements Database.Batchable <sObject>, Database.Stateful{
    public List<Contact> conList {get;set;}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, LeadSource, ConvertedDate FROM Lead WHERE ConvertedContactId != NULL';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        for(Lead ld : scope) {
            conList.add([SELECT FirstName, LastName 
                         FROM Contact 
                         WHERE Id IN (SELECT ConvertedContactId FROM Lead)]);
        }
    }
    global void Finish(Database.BatchableContext BC) {
       messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String body = 'FirstName ' +conList[0].FirstName+ 'LastName ' +conList[0].LastName+ 'done'; 
    }
}

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


Thanks and Regards,
Sachin Arora
www.sachinsf.com
 
SV MSV M
I see there are o errors while saving the code but the batch class was not running. Can you help me on this.