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
Abhishek AS 3Abhishek AS 3 

batch apex class to sync contact email with account email

My requirement is that there is a email field on contact. i have created a custom email field on Account. I want to search all accounts that have a matching email with a contact and add that account to the contacts lookup account field. If no such account exists with the same email then create a new account and add that account under the contact.
AnkaiahAnkaiah (Salesforce Developers) 
Hi Abhishek,

try with below code.
global class BatchApexExample implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        // collect the batches of records or objects to be passed to execute
         
        String query = 'SELECT Id,email FROM contact where AccountId=Null AND email!=Null';
        return Database.getQueryLocator(query);
    }
     
    global void execute(Database.BatchableContext BC, List<Contact> conlist) {
	
	set<string> emails = new set<string>();
	Map<string,Id> mapaccemailwithids = new map<string,id>();
	List<Account> createNewAcc = new List<Account>();
	Map<String,Contact> conNameKeys = new Map<String,Contact>();
        
        // process each batch of records default size is 200
        for(Contact con : conlist) {  
           emails.add(con.email);		

        }
		
		for(Account acc:[select id,custom_Email__c from account where custom_Email__c IN:emails ]){
		mapaccemailwithids.put(acc.custom_Email__c,acc.id);
		}
		
		for(contact con:conlist){
		if(mapaccemailwithids.containskey(con.email)){
		con.accountid = mapaccemailwithids.get(con.email);
		
		}
		if(!mapaccemailwithids.containskey(con.email)){
		 String emails = con.email;  
         conNameKeys.put(emails,con);
		Account acc = new Account();
		acc.Name = con.LastName;
		acc.custom_Email__c = con.email;
		createNewAcc.add(acc);
		}
		}
		
		insert createNewAcc;
		   for (Account acc : createNewAcc)   
                {  
                    system.debug('mapContainsKey ' + conNameKeys.containsKey(acc.custom_Email__c));
                   
                    if (conNameKeys.containsKey(acc.custom_Email__c))   
                    {  
                        conNameKeys.get(acc.custom_Email__c).accountId = acc.Id;  
                    }  
                }  
		
        try {
            // Update the Account Record
            update conlist;
         
        } catch(Exception e) {
            System.debug(e);
        }
         
    }   
     
    global void finish(Database.BatchableContext BC) {
        // execute any post-processing operations like sending email
    }
}

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​