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
si risi ri 

sending duplicate emails through apex

    I am trying to send an email to an Account related user lookup field whenever Opportunity stage moved to closed-won.But when I am fetching Account Id it is getting two times in debug statement and the mail is sending two times.I unable to figure out the issue can anyone guide me where I am doing wrong.
public static void notifyemail(List<Opportunity> newList){
        string  toEmailId ;
        set<Id> accid = new set<Id>();
    
      for(Opportunity opp : newList)
        {
            if(opp.AccountId != null)
            {
               accid.add(opp.AccountID);
            }
        }
     system.debug('accid************'+accid); // I am getting AccountID two times.
    if(accid.size()>0){
                 string testuserid= [Select Account.testuser__c from Opportunity Where accountid=:accid limit 1].Account.testuser__c;
                            string testuserEmail = [Select Email from User where Id=:testuserid limit 1].Email;
                         toEmailId  = testuserEmail;
                       system.debug('Ownerid************'+Ownerid);
                       system.debug('toEmailId************'+toEmailId);
    }
         if(toEmailId != null || toEmailId != '')
        {
            EmailTemplate template1;
            EmailTemplate emailTemplates = [ Select Body, HtmlValue, Id, Name, Subject from EmailTemplate  where Name='notification on Opportunity' Limit 1];
            List<Messaging.SingleEmailMessage> theEmails = new list<Messaging.SingleEmailMessage>();
            for(Opportunity op: newList){
                    list<string> emaillist= new list<string>();
                  emaillist.add(toEmailId);
                    string body = emailTemplates.Body;
                    string subject = emailTemplates.Subject;
                   
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setToAddresses(emaillist);
                    mail.setTemplateId(emailTemplates.Id);
                    mail.setSaveAsActivity(false);
                    mail.setSubject(subject);
                    mail.setPlainTextBody(body);
                   
                   theEmails.add(mail);
            }
        }
    } 
    
Trigger:
   if (Trigger.isAfter ){
        if (Trigger.isUpdate ){
             
            List<Opportunity> oplist = new list<opportunity>();
            for(opportunity op :trigger.new)
            {
                if( op.StageName == 'closed-won' && Trigger.oldmap.get(op.id).StageName!= op.closed-won)
                    oplist.add(op);
                
            }
            if(!oplist.isempty())
                EmailNotificationtcalss.notifyemail(Trigger.new);
            
        }