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. I just started writing tiggers and I am not sure how to get the code to work. I have found a few posts about the email trigger but I am very confused.
Thank you for any suggestions.
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, Email from Contact where email <> 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 o :Trigger.new)
{
if(o.Agent_Assigned__c != NULL)
(o.Referral_Fee__c = TRUE);
(o.stageName ='Agent Assigned');