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
Dorel4Dorel4 

email trigger from opportunity not using a custom field for the recipient

I am trying to create an apex email trigger on an Opportunity but have the recipient email come from a custom field called Agent email. I would like the email to be sent when the Stage is in 'Agent Accepted' to the email address in the field Agent Email. I have a template created for the body of the email but I can not pass the test. Almost the whole code is an error when I run the test.  Please help.

trigger AgentEmailfee on Opportunity  (after Insert,after update) {
                  EmailTemplate template = [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate 
                                            WHERE Name = 'Agent_Referral_Fee'];
//Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  //           mail.setTemplateId(template.id);
               
                              String subject = template.Subject;
subject = subject.replace('{!Opportunity.Name}','has been accepted'); 

 // Pick ca dummy Contact
 Opportunity o =[select id, Agent_Email__c from opportunity where Agent_Email__c <> null limit 1];

 // Construct the list of emails we want to send
 List <Messaging.SingleEmailMessage> lstMsgs = new List<Messaging.SingleEmailMessage>();

 Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
 msg.setTemplateId( [select id from EmailTemplate where DeveloperName='Agent_Referral_Fee'].id );
 msg.setWhatId( [select id from Opportunity limit 1].id );
 msg.setTargetObjectId(o.agent_email__c);
 msg.setToAddresses(new List<String>{''});

 lstMsgs.add(msg);

 // Send the emails in a transaction, then roll it back
 Savepoint sp = Database.setSavepoint();
 Messaging.sendEmail(lstMsgs);
 Database.rollback(sp);

     
 // For each SingleEmailMessage that was just populated by the sendEmail() method, copy its
 // contents to a new SingleEmailMessage. Then send those new messages.
 List<Messaging.SingleEmailMessage> lstMsgsToSend = new List<Messaging.SingleEmailMessage>();
 for (Messaging.SingleEmailMessage email : lstMsgs) {
 Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
 emailToSend.setToAddresses(email.getToAddresses());
 emailToSend.setPlainTextBody(email.getPlainTextBody());
 emailToSend.setHTMLBody(email.getHTMLBody());
 emailToSend.setSubject(email.getSubject());
 lstMsgsToSend.add(emailToSend);
 }
 Messaging.sendEmail(lstMsgsToSend);       
 for (opportunity op :Trigger.new)
    {
        if(op.Agent_Assigned__c != NULL)
            (op.Referral_Fee__c = TRUE);
            (op.stageName ='Agent Assigned');  }
}
ShashankShashank (Salesforce Developers) 
Are you saying that the test class is not covering the code? Or is the email noe being sent or is there as error message?