Write a Trigger to send an email to the account owner whenever the account’s industry is changed.

trigger SendIndustryChangeEmail on Account (before update) {   
	for (Account a : Trigger.new) {      
		Account oldAccount = Trigger.oldMap.get(a.Id);      
		if (a.Industry != oldAccount.Industry) {         
			Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();         
			email.setToAddresses(new String[] {a.Owner.Email});         
			email.setSubject('Industry Changed for Account: ' + a.Name);         
			email.setPlainTextBody('The industry of the account has changed from ' + 
							oldAccount.Industry +' to ' + a.Industry);         
			Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});      
		}   
	}
}



trigger and a separate class:


Trigger:

trigger SendIndustryChangeEmail on Account (before update) {
	IndustryChangeHandler handler = new IndustryChangeHandler();
	handler.sendIndustryChangeEmail(Trigger.new, Trigger.oldMap);
}




Class:

public class IndustryChangeHandler {
	public void sendIndustryChangeEmail(List newAccounts, Map oldAccountsMap) {
		for (Account newAccount : newAccounts) {
			Account oldAccount = oldAccountsMap.get(newAccount.Id);
			if (newAccount.Industry != oldAccount.Industry) {
				Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
				email.setToAddresses(new String[] {newAccount.Owner.Email});
				email.setSubject('Industry Changed for Account: ' + newAccount.Name);
				email.setPlainTextBody('The industry of the account has changed from ' + 
						oldAccount.Industry +' to ' + newAccount.Industry);
				Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
			}
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *