Scenario: When Opportunity get Closed Won send Email to Opportunity Owner.
OpportunityTrigger
trigger OpportunityTrigger on Opportunity (after update) {
OpportunityTriggerHandler handler = new OpportunityTriggerHandler();
if(trigger.isAfter && Trigger.isUpdate) {
handler.sendEmailWhenClosed(trigger.old, Trigger.newMap);
}
}
OpportunityTriggerHandler
public class OpportunityTriggerHandler {
public void sendEmailWhenClosed(List<Opportunity> lstOppor, Map<id, Opportunity> opprMap) {
for(Id opprId: opprMap.keySet()) {
if(opprMap.get(opprId).StageName == 'Closed Won') {
sendEmail(opprId);
}
}
List<Opportunity> oppr = [Select Id, OwnerId, StageName From Opportunity Where Id in:lstOppor];
}
public void sendEmail(Id OpportunityId) {
List<Opportunity> oppr = [Select Id, Name, OwnerId, StageName From Opportunity Where Id =: OpportunityId limit 1];
List<User> userDetail = [Select UserName, Email From User Where Id=: oppr[0].OwnerId limit 1];
List<Messaging.Email> emailList = new List<Messaging.Email>();
Messaging.SingleEmailMessage sendEmail = new Messaging.SingleEmailMessage();
sendEmail.setToAddresses(new String[] {userDetail[0].Email});
sendEmail.setSubject('Opportunity ' + oppr[0].Name + ' is Closed Won.');
String body = 'Dear ' + userDetail[0].UserName + ' Your Opportunity ' + oppr[0].Name + ' is Closed Won';
sendEmail.setHtmlBody(body);
emailList.add(sendEmail);
Messaging.sendEmail(emailList);
}
}