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
SFDC Apex DevSFDC Apex Dev 

trigger to send email notification using email template

I'm trying to write the below piece of code and calling it in after update context on opportunity.
I want to send email to the reciepient once the opportunity updated to stage 5 and product code on related opportunity product is STD.
I've created the email template as well and using the email tmplate id in the code but I'm not getting any email notification. Can anyone please help me out to correct the code?
public static void emailAlert(list<Opportunity> newOpportunityList, Map<Id,Opportunity> oldOpportunityMap){
        Set<id> OpptyId = new Set<id>();
        List<OpportunityLineItem> lstOptyLineItem = new List<OpportunityLineItem>();
        for(Opportunity ObjOppty: newOpportunityList){
            if(oldOpportunityMap.get(ObjOppty.Id).StageName != ObjOppty.StageName && ObjOppty.StageName == 'Won'){
        if(OpptyId.size() > 0){
          lstOptyLineItem = [Select id,Name,ProductCode from OpportunityLineItem where OpportunityId IN: OpptyId AND ProductCode = 'STD';    
        if(lstOptyLineItem.size() > 0){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>{''};
            //system.debug('to address'+ mail.setToAddresses);
            //system.debug('org address'+ mail.setOrgWideEmailAddressId);
           // mail.setTargetObjectId(primaryContact);
            List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
            system.debug('mail sent'+mail);
            try {
            } catch (Exception e) {

Please help me here to correct the above code.

Hi Chirag, 

Do you have a Stage on Opportunity called "Won"? 

If you're using the standard opportunity stages, then your condition should be 

if(oldOpportunityMap.get(ObjOppty.Id).StageName != ObjOppty.StageName && ObjOppty.StageName == 'Closed Won'){

SFDC Apex DevSFDC Apex Dev
Hi Vishal,

I've the stage name called won. I did some fixes and now I'm getting the notification email but it's not pulling any data.
When I was checking manually through email template it was pulling the data correctly.