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'){
                OpptyId.add(ObjOppty.id);
            }
        }
        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>{'cgupta@gmail.com'};
            mail.setTemplateId('00X02000000A34cEAC');
            mail.setToAddresses(sendTo);
            //system.debug('to address'+ mail.setToAddresses);
            mail.setOrgWideEmailAddressId(System.Label.Support_Email_Address);
            //system.debug('org address'+ mail.setOrgWideEmailAddressId);
           // mail.setTargetObjectId(primaryContact);
            List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
            allmsg.add(mail);
            system.debug('mail sent'+mail);
            try {
                Messaging.sendEmail(allmsg,false);
                return;
            } catch (Exception e) {
                System.debug(e.getMessage());
            }
        }
    }

Please help me here to correct the above code.
vishal-negandhivishal-negandhi

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.

Thanks!
Chirag