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
Richa Paliwal 18Richa Paliwal 18 

Apex trigger to send and email from opportunity based on certain fields on opportunity product

I need to send a HTML Email template when opportunity is marked closed won and 2 custom fields on opportunity products are set to 'yes'. Can someone please suggest me how can I achieve this? 
Raj VakatiRaj Vakati
You can able to do it using workflow or process builder 


https://help.salesforce.com/articleView?id=process_action_email.htm&type=5
https://help.mypurecloud.com/articles/use-process-builder-to-route-salesforce-emails/
https://automationchampion.com/tag/send-an-email-process-builder/
https://massmailer.io/blog/how-to-send-and-track-salesforce-workflow-email-alerts-through-process-builder/
https://www.marksgroup.net/blog/salesforce-com-using-process-builder-and-creating-an-email-alert-part-2/
Raj VakatiRaj Vakati
If you want trigger here is the sample code
 
trigger OpportunityEmail on Opportunity (after update) {

	  List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();

    for(Opportunity newItem : trigger.new) {


        
        if (newItem.StageName == 'Closed Won ' && OTHER CONDITIONS ) {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
List <Contact> Con= [select id, name from Contact where name =:'xx']; 
mail.setTargetObjectId(Con[0].id); 
mail.setSenderDisplayName('Salesforce Support'); 
mail.setUseSignature(false); 
mail.setBccSender(false); 
mail.setSaveAsActivity(false); 
EmailTemplate et=[Select id from EmailTemplate where Name=:'SFDC TEST']; 
mail.setTemplateId(et.id); 
          mails.add(mail);

        }
		}

Messaging.SendEmailResult [] r = Messaging.sendEmail(mails);

}

 
Richa Paliwal 18Richa Paliwal 18
@raj Actually , this needs to go based on fields from opportunity product, which is a child object of opportunity. process is not working in such case.

For eg. if someone is trying to mark the opportunity closed won and one of its product has a custom checkbox field checked, then trigger this email template that has merge fields of opportunity.
Richa Paliwal 18Richa Paliwal 18
This trigger also does not brings over opportunioty's merge field. Can anyone please help if you have any past experience?