+ Start a Discussion

Sending Email through Trigger When Opportunity Stage Changes

Hi All,

i need to Send an Email When Opportunity stage changes. for this i have Write one Class and Trigger. when i Tried to Insert or Update an Opportunity i have received below error

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger SendEmailToAccount caused an unexpected exception, contact your administrator: SendEmailToAccount: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing targetObjectId with template: []: Class.HelperContactTrigger.sendEmail: line 34, column 1

Apex Class:
public with sharing class HelperContactTrigger {
    public static List<Opportunity> sendEmail(List<Opportunity>Opportunities)
     //query on template object
        EmailTemplate et=[Select id from EmailTemplate where name=:'Approved By Manager'];

        //list of emails
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();   
        for(Opportunity Opp : Opportunities)
          //check for Account
            if(Opp.StageName =='Prospecting'|| Opp.StageName=='Qualification'){

                //initiallize messaging method
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

                //set object Id
                  List<String> sendTo = new List<String>();

                //set template Id

                //flag to false to stop inserting activity history

                //add mail
            //send mail

        return Opportunities;          
Apex Trigger:
trigger SendEmailToAccount on Opportunity (after insert,after update) 
        if(Trigger.isInsert )
            //helper class for single email but bulk messages
        if(trigger.isAfter && trigger.isUpdate )
I am trying to find out where are you checking the old value of a Stage? I mean you want to send an email whenever the opportunity changes correct!?

I would also suggest make a use of ISCHANGED() and PRIORVALUE() function in workflow and send an email notification from workflow and not from trigger. Trigger should be the last option Vasu.

If its still not resolved then try sending the requirement in little depth and we will see if this is possible via workflow or flow or via trigger.

Hope it helps!