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
MarcopppMarcoppp 

Sending alert on Opportunity change to Contacts

Hi,

I have a question, namely could somebody tell me the best way to send alert on Opportunity change to all Opportunity Contacts? Can this be done by trigger as below? although I could not get this working as I am getting an error on email, could somebody help me with this??

List<Opportunity> oList = Trigger.old;
List<Opportunity> nList = trigger.new;

  if(oList[0].StageName !=nList[0].StageName) {

      Set<Id> OpportunityIds= new Set<Id>();
      Map<id,Contact> ConMap = new Map<id,Contact>([select id,LastName,FirstName,email from Contact where Id in :OpportunityIds]);

      List<Contact>  sList = [select id,LastName,FirstName,email from Contact where Account.Id =:nList[0].accountid limit 1];

      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        mail.setSenderDisplayName('Salesforce Support');
        mail.setUseSignature(false);
        mail.setBccSender(false);
        mail.setSaveAsActivity(false);


      EmailTemplate et=[Select id from EmailTemplate limit 1];
      mail.setTemplateId(et.id);

      mail.setToAddresses(new String[] {sList[0].email});
      mail.setTargetObjectId(sList[0].id);
      mail.setSaveAsActivity(false);

      Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail}); 
     }
}

Thanks
Blake TanonBlake Tanon
What is the exact error?  I don't think you need this line mail.setToAddresses(new String[] {sList[0].email}) - since you are using a template the setTargetObjectId method takes care of the emails, your error also could be that the first row in slist (0) has a null email field.  You should add in your query email != null