I've just written my first batch which should change a contact's email from [email protected] to [email protected]
global class changeEmailAddressesToExampleInSandbox implements Database.Batchable<sObject> {
List<Contact> contactsEmails;
String tempEmail;
String newEmailDomain;
String query;
Integer totalNumOfContacts;
Integer counter;
global changeEmailAddressesToExampleInSandbox() {
newEmailDomain = '@example.com';
contactsEmails = new List<Contact>();
query = 'SELECT email FROM Contact';
tempEmail=' ';
totalNumOfContacts=[select count() from contact];
counter=0;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Contact> scope) { //changed Sobject to Contact
for(Contact con : scope){
tempEmail=con.Email;
if(!tempEmail.contains('@example.com')){
tempEmail = tempEmail.split('@')[0];
tempEmail+= newEmailDomain;
counter++;
}
contactsEmails.add(con);
}
}
global void finish(Database.BatchableContext BC) {
try{
update contactsEmails;
}
catch(Exception e){system.debug(e);}
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] { '[email protected]'};
message.optOutPolicy = 'FILTER';
message.subject = 'Email From New Sandbox';
message.plainTextBody = 'All contacts\' emails have been modified succesfully ' +'\n'+'The total number of contacts in the Sandbox is '+totalNumOfContacts+'\n'+counter+' contacts were updated';
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
if (results[0].success) {
System.debug('The email was sent successfully.');
} else {
System.debug('The email failed to send: ' + results[0].errors[0].message);
}
}
}
When I try to execute the following code on the Developer Console nothing happens, emails stay the same.
changeEmailAddressesToExampleInSandbox b = new changeEmailAddressesToExampleInSandbox();
Database.executeBatch(b);