0

I'm attempting to send a email alert via apex. Following is my code..

global class myARules{ 

public static void processMe(Set<Id> RIds) {
    Messaging.SingleEmailMessage[] mainlist = new Messaging.SingleEmailMessage[]{};                 
    List<Lead> myList = [SELECT Id FROM Lead WHERE Id IN: RIds];

    for (Lead l: myList) {

        myCSSettings__c cs = myCSSettings__c.getInstance(l.code__c);
        List<Group> Groupees = [SELECT Id, Email from Group where id = : cs.id__c];
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.assignmentRuleHeader.useDefaultRule = true;// use leadAssignment rules when updating
        l.setOptions(dmo);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();                
        String[] toAddresses = new String[] {Groupees[0].Email}; 
        Id templateId = [select id, name from EmailTemplate where developername = :Label.myEmailTemplte].id;
        mail.setToAddresses(toAddresses); 
        mail.setTargetObjectId(Groupees[0].Id);
        mail.setTemplateId(templateId);  
        mainlist.add(mail);                          
    }
     system.debug('@@mainlist'+mainlist);    
     system.debug('@@mainlistsize'+mainlist.size());     

    try{     
             system.debug('@@myList'+myList);
             update(myList);
          Messaging.sendEmail(mainlist);           
    } 

    catch (DmlException e){
            system.debug('@@Exception: '+e); 
    }
}
}

I am able to do all tasks except sending a mail. Assignment rules are firing as per requirement. Debug says @@mainlistsize is 0.

Also, a mail is sent if this for-loop is not present --> for (Lead l: myList)

I will be thankful if someone can point me to the right directin. Thanks in advance!

1
  • You declared the variable as maillist and adding the mail to mainlist Aug 18, 2016 at 14:50

1 Answer 1

2

According to the docs

setTargetObjectId(targetObjectId)

Required if using a template, optional otherwise. The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data.

However you are passing in the Id of a Group

List<Group> Groupees = [SELECT Id, Email from Group where id = : cs.id__c];
...
mail.setTargetObjectId(Groupees[0].Id);
1
  • I will ask a separate question because I don't want the email notification to be sent to this settargetobjectid's email, which is now sending.
    – MnZ
    Aug 19, 2016 at 6:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .