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
mat_tone_84mat_tone_84 

send email by a trigger starts 2 time!!

I have this trigger and if I test it, it will be send 2 email to the same "to address" why??

Where is the problem?

 

I try to change the event "before update" into "after update" but is the same, if I try to write after update and before update, the trigger send 4 emails!!

 

thanks

 

 

trigger nametrigger on Opportunity (before update) { list<opportunity> list_opp = new List<opportunity>(); for (opportunity o : Trigger.new) { list_opp.add(o); } list<opportunity> list_opp_old = new List<opportunity>(); for (opportunity o_old : Trigger.old) { list_opp_old.add(o_old); } if (list_opp.get(0).fieldx__c == true & list_opp.get(0).fieldx <> list_opp_old.get(0).fieldx ){ Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {'testemail@xxx.com'}; mail.setToAddresses(toAddresses ); mail.setReplyTo('testemail@xxx.com'); mail.setSenderDisplayName('testsender@xxx.com'); mail.setSubject('fax'); mail.setPlainTextBody(''); Attachment Att = [Select body, name from attachment where parent.id = :list_opp.get(0).id and name like 'richiestace%' order by lastmodifieddate desc limit 1]; Messaging.EmailFileAttachment[] fileAttachments = new Messaging.EmailFileAttachment[1]; Messaging.EmailFileAttachment fileAttachment = new Messaging.EmailFileAttachment(); fileAttachment.setBody(Att.body); fileAttachment.setFileName(Att.name); fileAttachments[0] = fileAttachment; mail.setFileAttachments(fileAttachments); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }

 

 

Best Answer chosen by Admin (Salesforce Developers) 
mat_tone_84mat_tone_84

I solve the problem by insert this line into the "if":

 

 

list_opp.get(0).fieldx__c = false;

 

 in this way SF send only one email

 

All Answers

mat_tone_84mat_tone_84

I solve the problem by insert this line into the "if":

 

 

list_opp.get(0).fieldx__c = false;

 

 in this way SF send only one email

 

This was selected as the best answer
jack huangjack huang

Hi, I had used your code from a custome object for a test After Insert, but can not get any email. how should i do then I can get the email.