+ Start a Discussion
Peter BölkePeter Bölke 

Triggerproblem : Double send emails

Hello,

i have problem, with my Triggern. It sends all Emails twice, and i can't find a reason for this behaviour

trigger:
trigger TrgKnowledgeSendNotification on Knowledge__kav (after update, after insert) {
    System.debug('TRIGGER :: ' + Trigger.New);
    System.debug('TRIGGER :: ' + Trigger.Old);
    System.debug('TRIGGER COMP ' + (Trigger.Old == Trigger.New));
    id acId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('abc').getRecordTypeId();
    System.debug('ACID :: ' + acId);
    id kaId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('xyz').getRecordTypeId();
    System.debug('KaID :: ' + kaId);
    System.debug('PUBLISH COMPARE :: ' + (Trigger.New[0].PublishStatus =='Online'));
    if(KnowledgebaseMailTriggerHandler.isFirstTime && Trigger.New[0].Approved__c == true){    
        KnowledgebaseMailTriggerHandler.isFirstTime =false;
        if(Trigger.New[0].ValidationStatus == 'Validated' && Trigger.New[0].RecordTypeId == acId){ //Trigger.New[0].ValidationStatus == 'Validated' &&
            KnowledgebaseMailTriggerHandler kmth = new KnowledgebaseMailTriggerHandler();
            try{
                kmth.sendAcPartnerPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                System.debug('SEND FAIL ' + ex.getStackTraceString());
            }
            try{
                kmth.sendAcInternalPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                
                System.debug('SEND FAIL ' + ex.getStackTraceString());
                
            }  
        }
        else if(Trigger.New[0].ValidationStatus == 'Validated' && Trigger.New[0].RecordTypeId == kaId ){//&& Trigger.New[0].PublishStatus == 'Online'
            KnowledgebaseMailTriggerHandler kmth = new KnowledgebaseMailTriggerHandler();
            try{
                kmth.sendKartPartnerPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                System.debug('SEND FAIL ' + ex.getStackTraceString());
            }
            try{
                kmth.sendKartInternalPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                
                System.debug('SEND FAIL ' + ex.getStackTraceString());
            }
            
        }
    }
}

trigger handler
 
public class KnowledgebaseMailTriggerHandler {
    
    public static Boolean isFirstTime = true;
    
    
    public void sendAcPartnerPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setCcAddresses(null);
        mail.setToAddresses(null);
        mail.setBccAddresses(getEmailAddresses('abc Partners'));
        mail.setTargetObjectId(userinfo.getUserId());
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject from EmailTemplate where Name='AC_AUTO_ArticlePublication'];
        
        mail.setTemplateId(et.id);
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null || article.Publication_Type__c != '') {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
            //htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c', host+'portalLightning/s/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        
        mail.setHtmlBody(htmlBody);
        System.debug('MAIL ' + mail);
        if (mail.getBccAddresses().size() != null && mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
                else{
                    User[] usr = [SELECT email FROM user WHERE Username like '%abilex%' Limit 1];
                    List<String> mailToAddresses = new List<String>();
                    for (User u : usr){
                        mailToAddresses.add(u.Email);
                    }
                    mail.setBccAddresses(mailToAddresses);
                    System.debug(usr);
                    System.debug(mailToAddresses);
                    System.debug('tesmtail '+ mail);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
        
    }
    
    public void sendAcInternalPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setCcAddresses(null);
        mail.setToAddresses(null);
        mail.setBccAddresses(getEmailAddresses('abc Business'));
        mail.setTargetObjectId(userinfo.getUserId());
        //mail.setSenderDisplayName('Salesforce Support');
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject  from EmailTemplate where Name='AC_AUTO_ArticlePublication_Internal'];
        
        mail.setTemplateId(et.id);
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        mail.setHtmlBody(htmlBody);
        System.debug('MAIL ' + mail);
        if (mail.getBccAddresses().size() != null &&mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
        
    }
    
    public void sendKartPartnerPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        //mail.setAddresses(false);
        mail.setTargetObjectId(userinfo.getUserId());
        mail.setBccSender(true);
        //mail.setSenderDisplayName('Salesforce Support');
        mail.setUseSignature(false);
        mail.setBccAddresses(getEmailAddresses('xyz Partners'));
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject from EmailTemplate where Name='KA_AUTO_ArticlePublication'];
        mail.setTemplateId(et.id);
        
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
            //htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c', article.Link_to_Knowledge_Article__c);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        mail.setHtmlBody(htmlBody);
        if (mail.getBccAddresses().size() != null &&mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
    }
    
    public void sendKartInternalPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(userinfo.getUserId());
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject from EmailTemplate where Name='KA_AUTO_ArticlePublication_Internal'];
        mail.setBccAddresses(getEmailAddresses('xyz Business'));
        mail.setTemplateId(et.id);
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
            //htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c', article.Link_to_Knowledge_Article__c);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        mail.setHtmlBody(htmlBody);
        if (mail.getBccAddresses().size() != null &&mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
    }
    
    public List<String> getEmailAddresses(String groupname) {
        
        List<String> idList = new List<String>();
        List<String> mailToAddresses = new List<String>();
        Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = :groupname];
        for (GroupMember gm : g.groupMembers) {
            
			//System.debug('object is '+ gm.userOrGroupId.getsobjecttype());
            idList.add(gm.userOrGroupId);
        }
        
        User[] usr = [SELECT id, email FROM user WHERE id IN :idList];
        for (User u : usr) {
            if(UserInfo.getUserId() != u.id){
                mailToAddresses.add(u.email);
            }
        }
        Set<String> myset = new Set<String>();
        List<String> result = new List<String>();
        myset.addAll(mailToAddresses);
        result.addAll(myset);
        system.debug('MAIL RECIEPTS :: ' + result.size());
        system.debug('MAIL RECIEPTS :: ' + result);
        return result;
        
    }
}
Can someone give an advise

thanks!
 
Steven NsubugaSteven Nsubuga
1 possibility is that your trigger runs twice. This happens when there is a field update or process that updates a field on the object on which your trigger runs. This would cause the trigger to run twice. 
See this documentation here https://help.salesforce.com/articleView?id=000005328&type=1
Peter BölkePeter Bölke
Hello Steven,

thanks for your answer i am using 
 
public static Boolean isFirstTime = true;

for this.  But it doesnt help.