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
Salesforce BlitzSalesforce Blitz 

send a list of users to email body

 I have  a user list. I need this user list to be passed to sendemail method, so that the user names are displayed in the email body as below:

 "There has been no activity from the following sales people of your team:
1. User1
2. User2
3.User 3 …….  "  


Could you please let me know as of how to achieve this/could yo send any relevent code which would be helpful.


 Thanks in adv
Best Answer chosen by Salesforce Blitz
Fahad-AkhtarFahad-Akhtar
Hi Jagadish,
Code will check if any of their subordinate have not edited any record in last seven days and only then add their lead to list to send email. Check this code out.
 
Global class MyClass implements schedulable {
    
    Global void execute(schedulablecontext SC)
    {
     
        date d = system.today().addDays(-7);
        List<Account> acclist=  [select id,name,LastModifiedById from account where LastModifiedDate >:d];
  
        List<Opportunity> opplist=  [select id,name,LastModifiedById from Opportunity where LastModifiedDate >:d];
        List<Contact> conlist=  [select id,name,LastModifiedById from Contact where LastModifiedDate >:d];
        List<Lead> leadlist=  [select id,name,LastModifiedById from Lead where LastModifiedDate >:d];
       // List<activity> actlist = [select id,name,LastModifiedById from Activity where LastModifiedDate >:d]
        
        set<id> accset = new set<Id>();
        for(Account Acc : acclist){ accset.add(acc.LastModifiedById); }
           set<id> oppset = new set<Id>();
        for(Opportunity Opp : opplist){ oppset.add(opp.LastModifiedById); }
        set<id> conset = new set<Id>();
        for(contact con : conlist){ conset.add(con.LastModifiedById); }
        set<id> leadset = new set<Id>();
        for(lead ld : leadlist){ leadset.add(ld.LastModifiedById); }
        
        
        List<Id> subordlist=new List<Id>();
        List<id> unediteduseridlist = new List<id>();
        List<user> uneditedusernamelist= new List<user>();    
        Set<String> set_TeamleadEmailAddress = new Set<String>(); 
        List<user> TLSPuserlist = [Select id,Name from User where UserRole.Name =: 'Label.Chief'];
       
        for(user u : TLSPuserlist)
        {
            set<id> subord= new set<id>();
            subord=Roleutils.getRoleSubordinateUsers(u.Id);
            
            If(subord.size()>0 && subord!=NULL)
            {
               for(Id id1 : subordlist)
               {
                If(!accset.contains(id1) || !oppset.contains(id1) || conset.contains(id1) || leadset.contains(id1))
               { 
                  lst_TeamleadEmailAddress.add(u.email);
                  unediteduseridlist.add(id1);
               }
           }
           } 
       }
         sendmail(unediteduseridlist,lst_TeamleadEmailAddress);       
     }
   public void sendmail(List<id> lst_userid, Set<String> set_teamlead)
                {
                  Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                  email.setSubject('CRM not updated this week');
                  String s = 'There has been no activity from the following sales people of your team: <br/>';
                  Integer i = 0;
                  for(user u : [SELECT id,firstname,lastname FROM user WHERE id=:unediteduseridlist]){
                  i++;
                  s += String.ValueOf(i) + '. ' + u.FirstName + ' ' + u.LastName + '<br/>';
                  }

                  email.setPlainTextBody(s);
                  email.setToAddresses(lst_teamlead);
                  Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email}); 
                }
}

Thanks,
Fahad Akhtar

All Answers

Fahad-AkhtarFahad-Akhtar
Hi Jagadish Jagz,
Try below code in developer console and replace "Test@hotmail.com" with your actial email address and this should work.
 
// First, reserve email capacity for the current Apex transaction to ensure
// that we won't exceed our daily email limits when sending email after
// the current transaction is committed.
Messaging.reserveSingleEmailCapacity(2);

// Processes and actions involved in the Apex transaction occur next,
// which conclude with sending a single email.

// Now create a new single email message object
// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

// Strings to hold the email addresses to which you are sending the email.
String[] toAddresses = new String[] {'Test@hotmail.com'}; 
String[] ccAddresses = new String[] {'Test@hotmail.com'};
  

// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);

// Specify the address used when the recipients reply to the email. 
mail.setReplyTo('support@acme.com');

// Specify the name used as the display name.
mail.setSenderDisplayName('Salesforce Support');

// Specify the subject line for your email address.
mail.setSubject('New Case Created : ');

// Set to True if you want to BCC yourself on the email.
mail.setBccSender(false);

// Optionally append the salesforce.com email signature to the email.
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);
String s = 'There has been no activity from the following sales people of your team: <br/>';
Integer i = 0;
for(user u : [SELECT id,firstname,lastname FROM user LIMIT 10]){
    i++;
    s += String.ValueOf(i) + '. ' + u.FirstName + ' ' + u.LastName + '<br/>';
}
// Specify the text content of the email.
mail.setPlainTextBody(s);

mail.setHtmlBody(s);

// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Thanks,
Fahad Akhtar
Amit Chaudhary 8Amit Chaudhary 8
Please try Visualforce email template for same.
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_email_templates_creating.htm
https://developer.salesforce.com/page/VisualForceEmailTemplates_sample

One Sample with Contact and Case record.
<messaging:emailTemplate recipientType="Contact"
  relatedToType="Account"
  subject="Case report for Account: {!relatedTo.name}"
  replyTo="support@acme.com">
  <messaging:htmlEmailBody>
    <html>
      <body>
        <STYLE type="text/css">
          TH {font-size: 11px; font-face: arial;background: #CCCCCC;
               border-width: 1;  text-align: center } 
          TD  {font-size: 11px; font-face: verdana } 
          TABLE {border: solid #CCCCCC; border-width: 1}
          TR {border: solid #CCCCCC; border-width: 1}
        </STYLE>
        <font face="arial" size="2">
          <p>Dear {!recipient.name},</p>
          <p>Below is a list of cases related to the account: {!relatedTo.name}.</p>
          <table border="0" >
            <tr > 
               <th>Action</th>
               <th>Case Number</th>
               <th>Subject</th>
               <th>Creator Email</th>
               <th>Status</th>
            </tr>
            <apex:repeat var="cx" value="{!relatedTo.Cases}">
              <tr>
                <td><a href="https://na1.salesforce.com/{!cx.id}">View</a> |  
                <a href="https://na1.salesforce.com/{!cx.id}/e">Edit</a></td>
                <td>{!cx.CaseNumber}</td>
                <td>{!cx.Subject}</td>
                <td>{!cx.Contact.email}</td>
                <td>{!cx.Status}</td>
              </tr>
            </apex:repeat>                 
          </table>
          <p />
        </font>
      </body>
    </html>
  </messaging:htmlEmailBody> 
  <messaging:plainTextEmailBody >
    Dear {!recipient.name},
    
    Below is a list of cases related to Account: {!relatedTo.name}
    
    [ Case Number ] - [ Subject ] - [ Email ] - [ Status ]
    
    <apex:repeat var="cx" value="{!relatedTo.Cases}">
      [ {!cx.CaseNumber} ] - [ {!cx.Subject} ] - [ {!cx.Contact.email} ] - [ {!cx.Status} ]
    </apex:repeat>
    
    For more information login to http://www.salesforce.com
  </messaging:plainTextEmailBody>    
</messaging:emailTemplate>
Please let us know if this will help you

Thanks
Amit Chaudhary
 
ManojjenaManojjena
Hi Jagdish,

Try with below code it will help you .
 
List<String> strList=new List<String>{'Apple','Banana','Cocunut'};

for(Integer count=1;count<=strList.size();count++){
System.debug(count+'.'+strList.get(count-1)+'\n');
    }
Replace this list with your user name list .pass that list in your mathod .
Then in your email body manipulate like above .
Check in developer console ,let me know if it helps .

Thanks
Manoj
 
Salesforce BlitzSalesforce Blitz
Hi  Fahad Akhtar,

Thanks for the code, that helped a bit in email body.

I need top pass list(userlist which holds multiiple user names) to this sendemail method. 
Can I pass a list as parameter to sendemail method.?

Or how it should be done.?


Thanks,
jagadish jagz
Fahad-AkhtarFahad-Akhtar
Hi Jagadish,
Not sure, if i got your question correctly, let me try. sendEmail method expect list of "SingleEmailMessage" object, it will not accpet a list of user name, if you are questions is that you need to send email to multiple users you can pass a list of email addresses 
mail.setToAddresses(<List of email address here>);
if your question is that you have a list of username as string, you can do something link this
 
// First, reserve email capacity for the current Apex transaction to ensure
// that we won't exceed our daily email limits when sending email after
// the current transaction is committed.
Messaging.reserveSingleEmailCapacity(2);

// Processes and actions involved in the Apex transaction occur next,
// which conclude with sending a single email.

// Now create a new single email message object
// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

// Strings to hold the email addresses to which you are sending the email.
String[] toAddresses = new String[] {'Test@hotmail.com'}; 
String[] ccAddresses = new String[] {'Test@hotmail.com'};
  

// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);

// Specify the address used when the recipients reply to the email. 
mail.setReplyTo('support@acme.com');

// Specify the name used as the display name.
mail.setSenderDisplayName('Salesforce Support');

// Specify the subject line for your email address.
mail.setSubject('New Case Created : ');

// Set to True if you want to BCC yourself on the email.
mail.setBccSender(false);

// Optionally append the salesforce.com email signature to the email.
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);
List<String> lst_s = new List<String>();
lst_s.add('user 1');
lst_s.add('user 2');
lst_s.add('user 3');

String s = 'There has been no activity from the following sales people of your team: <br/>';
Integer i = 0;
for(String u :lst_s){
    i++;
    s += String.ValueOf(i) + '. ' + u + '<br/>';
}
// Specify the text content of the email.
mail.setPlainTextBody(s);

mail.setHtmlBody(s);

// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Thanks,
Fahad Akhtar
Salesforce BlitzSalesforce Blitz
Let me explain..I need to fetch all users below an user role(Sales VP)  in role heirarchy and send a mail to sales VP mail ID,  specifting him that these are list of users below you who did not edit any records in the last one week.


I guess I have coded to an extent to retreive VP(I specified Custom Label) and pass his Id to utility class which returns set of all users below him in heirarchy.

I am processing them and adding ton list if they did not modify any record in last week.


Now I need this list to be passed to sendemail method, andmention all users who did not modify any records in the EMAIL BODY.
The list which holds ids are below in unediteduseridlist.

This class needs to be scheduled weekly. So implemented schedulable and did code in execute() method. I guess this is fine
Hope you got my task. Kindly let me know if there are any changed rerquired.

Thanks in advance,.


CLASS:

Global class MyClass implements schedulable {
    
    Global void execute(schedulablecontext SC)
    {
     
        date d = system.today().addDays(-7);
        List<Account> acclist=  [select id,name,LastModifiedById from account where LastModifiedDate >:d];
  
        List<Opportunity> opplist=  [select id,name,LastModifiedById from Opportunity where LastModifiedDate >:d];
        List<Contact> conlist=  [select id,name,LastModifiedById from Contact where LastModifiedDate >:d];
        List<Lead> leadlist=  [select id,name,LastModifiedById from Lead where LastModifiedDate >:d];
       // List<activity> actlist = [select id,name,LastModifiedById from Activity where LastModifiedDate >:d]
        
        set<id> accset = new set<Id>();
        for(Account Acc : acclist){ accset.add(acc.LastModifiedById); }
           set<id> oppset = new set<Id>();
        for(Opportunity Opp : opplist){ oppset.add(opp.LastModifiedById); }
        set<id> conset = new set<Id>();
        for(contact con : conlist){ conset.add(con.LastModifiedById); }
        set<id> leadset = new set<Id>();
        for(lead ld : leadlist){ leadset.add(ld.LastModifiedById); }
        
        
        List<Id> subordlist=new List<Id>();
        List<id> unediteduseridlist = new List<id>();
        List<user> uneditedusernamelist= new List<user>();    
        List<user> TLSPuserlist=[Select id,Name from User where UserRole.Name =: 'Label.Chief'];
       
        for(user u : TLSPuserlist)
        {
            set<id> subord= new set<id>();
            subord=Roleutils.getRoleSubordinateUsers(u.Id);
            
            If(subord.size()>0 && subord!=NULL)
            {
               for(Id id1 : subordlist)
               {
                If(!accset.contains(id1) || !oppset.contains(id1) || conset.contains(id1) || leadset.contains(id1))
               { 
                   unediteduseridlist.add(id1);
               }
           }
           } 
       }
                
     }
   public void sendmail()
                {
                  Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                  string [] toaddress= New string[]{''};
                  email.setSubject('CRM not updated this week');
                  String s = 'There has been no activity from the following sales people of your team: <br/>';
                  Integer i = 0;
                  for(user u : [SELECT id,firstname,lastname FROM user LIMIT 10]){
                  i++;
                  s += String.ValueOf(i) + '. ' + u.FirstName + ' ' + u.LastName + '<br/>';
                  }

                  email.setPlainTextBody(s);
                  email.setToAddresses(toaddress);
                  Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email}); 
                }
}




--------------------------------------------------------
RoleUtils CLASS:

public with sharing class RoleUtils {

  public static Set<ID> getRoleSubordinateUsers(Id userId) {

    // get requested user's role
    Id roleId = [select UserRoleId from User where Id = :userId].UserRoleId;
    // get all of the roles underneath the user
    Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{roleId});
    // get all of the ids for the users in those roles
    Map<Id,User> users = new Map<Id, User>([Select Id, Name From User where 
      UserRoleId IN :allSubRoleIds]);
    // return the ids as a set so you can do what you want with them
    return users.keySet();

  }

  private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) {

    Set<ID> currentRoleIds = new Set<ID>();

    // get all of the roles underneath the passed roles
    for(UserRole userRole :[select Id from UserRole where ParentRoleId IN :roleIds AND ParentRoleID != null])
    currentRoleIds.add(userRole.Id);

    // go fetch some more rolls!
    if(currentRoleIds.size() > 0)
      currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds));

    return currentRoleIds;

  }

}
Fahad-AkhtarFahad-Akhtar
Hi Jagadish,
I have made following changes in your code:
1) Added a parameter to your send email method
2) Pass your list of ids to your send email method
3) add a filter to your user query
 
Global class MyClass implements schedulable {
    
    Global void execute(schedulablecontext SC)
    {
     
        date d = system.today().addDays(-7);
        List<Account> acclist=  [select id,name,LastModifiedById from account where LastModifiedDate >:d];
  
        List<Opportunity> opplist=  [select id,name,LastModifiedById from Opportunity where LastModifiedDate >:d];
        List<Contact> conlist=  [select id,name,LastModifiedById from Contact where LastModifiedDate >:d];
        List<Lead> leadlist=  [select id,name,LastModifiedById from Lead where LastModifiedDate >:d];
       // List<activity> actlist = [select id,name,LastModifiedById from Activity where LastModifiedDate >:d]
        
        set<id> accset = new set<Id>();
        for(Account Acc : acclist){ accset.add(acc.LastModifiedById); }
           set<id> oppset = new set<Id>();
        for(Opportunity Opp : opplist){ oppset.add(opp.LastModifiedById); }
        set<id> conset = new set<Id>();
        for(contact con : conlist){ conset.add(con.LastModifiedById); }
        set<id> leadset = new set<Id>();
        for(lead ld : leadlist){ leadset.add(ld.LastModifiedById); }
        
        
        List<Id> subordlist=new List<Id>();
        List<id> unediteduseridlist = new List<id>();
        List<user> uneditedusernamelist= new List<user>();    
        List<user> TLSPuserlist=[Select id,Name from User where UserRole.Name =: 'Label.Chief'];
       
        for(user u : TLSPuserlist)
        {
            set<id> subord= new set<id>();
            subord=Roleutils.getRoleSubordinateUsers(u.Id);
            
            If(subord.size()>0 && subord!=NULL)
            {
               for(Id id1 : subordlist)
               {
                If(!accset.contains(id1) || !oppset.contains(id1) || conset.contains(id1) || leadset.contains(id1))
               { 
                   unediteduseridlist.add(id1);
               }
           }
           } 
       }
         sendmail(unediteduseridlist);       
     }
   public void sendmail(List<id> lst_userid)
                {
                  Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                  string [] toaddress= New string[]{''};
                  email.setSubject('CRM not updated this week');
                  String s = 'There has been no activity from the following sales people of your team: <br/>';
                  Integer i = 0;
                  for(user u : [SELECT id,firstname,lastname FROM user WHERE id=:unediteduseridlist]){
                  i++;
                  s += String.ValueOf(i) + '. ' + u.FirstName + ' ' + u.LastName + '<br/>';
                  }

                  email.setPlainTextBody(s);
                  email.setToAddresses(toaddress);
                  Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email}); 
                }
}

Thanks,
Fahad Akhtar
Fahad-AkhtarFahad-Akhtar
Hi Jagadish,
Please mark one best answer, if this has solved your problem.

Thanks,
​Fahad Akhtar
Salesforce BlitzSalesforce Blitz
Hi Fahad,.

In this case i need to pass the email of the id1 to sendmail alomg with the list.

How can i send the email id of the id1 user..(I need to pass the email id of id1 user to sendmail method. And then need to set it as toaddress , so that email will go to respective Team lead)
Fahad-AkhtarFahad-Akhtar
Hi Jagadish,
unediteduseridlist is a list of user who have not updated the CRM in last seven days, you want send email to their team lead and not to themselves is that correct or are you looking to send an email to themselves?

Thanks,
Fahad Akhtar
Salesforce BlitzSalesforce Blitz
YES....I need to send email to the Team lead (A Single mail which includes all names of the users below him, who did not edit the records in last one week.)
Fahad-AkhtarFahad-Akhtar
Hi Jagadish,
Code will check if any of their subordinate have not edited any record in last seven days and only then add their lead to list to send email. Check this code out.
 
Global class MyClass implements schedulable {
    
    Global void execute(schedulablecontext SC)
    {
     
        date d = system.today().addDays(-7);
        List<Account> acclist=  [select id,name,LastModifiedById from account where LastModifiedDate >:d];
  
        List<Opportunity> opplist=  [select id,name,LastModifiedById from Opportunity where LastModifiedDate >:d];
        List<Contact> conlist=  [select id,name,LastModifiedById from Contact where LastModifiedDate >:d];
        List<Lead> leadlist=  [select id,name,LastModifiedById from Lead where LastModifiedDate >:d];
       // List<activity> actlist = [select id,name,LastModifiedById from Activity where LastModifiedDate >:d]
        
        set<id> accset = new set<Id>();
        for(Account Acc : acclist){ accset.add(acc.LastModifiedById); }
           set<id> oppset = new set<Id>();
        for(Opportunity Opp : opplist){ oppset.add(opp.LastModifiedById); }
        set<id> conset = new set<Id>();
        for(contact con : conlist){ conset.add(con.LastModifiedById); }
        set<id> leadset = new set<Id>();
        for(lead ld : leadlist){ leadset.add(ld.LastModifiedById); }
        
        
        List<Id> subordlist=new List<Id>();
        List<id> unediteduseridlist = new List<id>();
        List<user> uneditedusernamelist= new List<user>();    
        Set<String> set_TeamleadEmailAddress = new Set<String>(); 
        List<user> TLSPuserlist = [Select id,Name from User where UserRole.Name =: 'Label.Chief'];
       
        for(user u : TLSPuserlist)
        {
            set<id> subord= new set<id>();
            subord=Roleutils.getRoleSubordinateUsers(u.Id);
            
            If(subord.size()>0 && subord!=NULL)
            {
               for(Id id1 : subordlist)
               {
                If(!accset.contains(id1) || !oppset.contains(id1) || conset.contains(id1) || leadset.contains(id1))
               { 
                  lst_TeamleadEmailAddress.add(u.email);
                  unediteduseridlist.add(id1);
               }
           }
           } 
       }
         sendmail(unediteduseridlist,lst_TeamleadEmailAddress);       
     }
   public void sendmail(List<id> lst_userid, Set<String> set_teamlead)
                {
                  Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                  email.setSubject('CRM not updated this week');
                  String s = 'There has been no activity from the following sales people of your team: <br/>';
                  Integer i = 0;
                  for(user u : [SELECT id,firstname,lastname FROM user WHERE id=:unediteduseridlist]){
                  i++;
                  s += String.ValueOf(i) + '. ' + u.FirstName + ' ' + u.LastName + '<br/>';
                  }

                  email.setPlainTextBody(s);
                  email.setToAddresses(lst_teamlead);
                  Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email}); 
                }
}

Thanks,
Fahad Akhtar
This was selected as the best answer
Salesforce BlitzSalesforce Blitz
Almost done fahad,,But getting below error;

Method does not exist or incorrect signature: [Messaging.SingleEmailMessage].setToAddresses(Set&lt;String&gt;)

Rather than passing a set<string> we can pass a simple string as we need pass single email address(TL address) at a time..I guess
Fahad-AkhtarFahad-Akhtar
You can create a list in your sendemail method and use AddAll list method to add your set to the list and try passing list to 
setToAddresses method,this shoudl work as String and list should be same.

Thanks,
Fahad Akhtar
Salesforce BlitzSalesforce Blitz
Thanks Fahad..It worked..

One more thing is like..

I have role heirarchies multiple level deep..
                              A
                               |
           -----------------------------------
           |         |        |      |       |
           B       C      D      E     F
           |
---------------------
|          |         |   
B1     B2      B3


I have role heirarchy defined as above.

Through above code I guess I can only get olny upto one level deep.

But I need to go multiple levels deep.(n levels)

If users(B,C,D,E,F) did not edit record in last one week, mail will be sent to A.  That works fine.


What i need is I need to query B1 B2 B3 ...  and send mail to B as well.


A recursive call has to be made to util functiion n check should be implemented I guess..

where should I modify the code....Any suggestion./help??
Fahad-AkhtarFahad-Akhtar
Hi Jadadish,
This should be easy as you can query all roles
 
select Id,ParentRoleId from UserRole

and create a map, put parentid as a key and all child as a list<ids>,loop through your all the child record for the same parent and check the same logic as you already have, you can use a where clause to only work for certain roles and also your send email code will also be in a loop of your map which will only send email to one parent role of their respective subordinate have inactivity for last seven days.

Thanks,
Fahad Akhtar
Salesforce BlitzSalesforce Blitz
Hi Fahad,

I tried modifying the code, But its not working as expected,

Could you please modify and add those couuple of lines of code if possible..Thanks a lot ...
Fahad-AkhtarFahad-Akhtar
Hi Jgadish,
I have created a map which will have parentroleid as a key and list of all direct subordinate ids as list, you can use map.keyset() to query all the user with parents record id and use filter role query by role name, one you query all the subrodiate you can use the same logic to identofy if they have modified any record and send a seprate email to all map keys for their suboridinates, attached is a basic sample code.
 
Global class MyClass implements schedulable {
    
    Global void execute(schedulablecontext SC)
    {
     
        date d = system.today().addDays(-7);
        List<Account> acclist=  [select id,name,LastModifiedById from account where LastModifiedDate >:d];
  
        List<Opportunity> opplist=  [select id,name,LastModifiedById from Opportunity where LastModifiedDate >:d];
        List<Contact> conlist=  [select id,name,LastModifiedById from Contact where LastModifiedDate >:d];
        List<Lead> leadlist=  [select id,name,LastModifiedById from Lead where LastModifiedDate >:d];
       // List<activity> actlist = [select id,name,LastModifiedById from Activity where LastModifiedDate >:d]
        
        set<id> accset = new set<Id>();
        for(Account Acc : acclist){ accset.add(acc.LastModifiedById); }
           set<id> oppset = new set<Id>();
        for(Opportunity Opp : opplist){ oppset.add(opp.LastModifiedById); }
        set<id> conset = new set<Id>();
        for(contact con : conlist){ conset.add(con.LastModifiedById); }
        set<id> leadset = new set<Id>();
        for(lead ld : leadlist){ leadset.add(ld.LastModifiedById); }
        
        
        List<Id> subordlist=new List<Id>();
        List<id> unediteduseridlist = new List<id>();
        List<user> uneditedusernamelist= new List<user>();    
        Set<String> set_TeamleadEmailAddress = new Set<String>();
        map<String,list<id>> map_userrole = new map<String,list<id>>();
        list<id> lst_id = new list<id>(); 
        for(UserRole u : [select Id,ParentRoleId from UserRole]){
          if(map_userrole.containsKey(u.ParentRoleId)){
            map_userrole.get(u.ParentRoleId).add(u.id);
          }else{
            lst_id = new lst_id<id>;
            lst_id.add(u.id);
            map_userrole.put(u.ParentRoleId,lst_id);            
          }
        }
        List<user> TLSPuserlist = [Select id,Name from User where UserRole.Name =: 'Label.Chief'];
       
        for(user u : TLSPuserlist)
        {
            set<id> subord= new set<id>();
            subord=Roleutils.getRoleSubordinateUsers(u.Id);
            
            If(subord.size()>0 && subord!=NULL)
            {
               for(Id id1 : subordlist)
               {
                If(!accset.contains(id1) || !oppset.contains(id1) || conset.contains(id1) || leadset.contains(id1))
               { 
                  lst_TeamleadEmailAddress.add(u.email);
                  unediteduseridlist.add(id1);
               }
           }
           } 
       }
         sendmail(unediteduseridlist,lst_TeamleadEmailAddress);       
     }
   public void sendmail(List<id> lst_userid, Set<String> set_teamlead)
                {
                  Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                  email.setSubject('CRM not updated this week');
                  String s = 'There has been no activity from the following sales people of your team: <br/>';
                  Integer i = 0;
                  for(user u : [SELECT id,firstname,lastname FROM user WHERE id=:unediteduseridlist]){
                  i++;
                  s += String.ValueOf(i) + '. ' + u.FirstName + ' ' + u.LastName + '<br/>';
                  }

                  email.setPlainTextBody(s);
                  email.setToAddresses(lst_teamlead);
                  Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email}); 
                }
}

Thanks,
Fahad Akhtar
Salesforce BlitzSalesforce Blitz
Hi Fahad,


The code below (Util Class) only gives the ids of the Rolenames (All roles..multiple levels deep) ..
NOT THE USERS IDs below that Role.


Could you provide code which fetches me the users below passed Role. through the userroleid??

Thanks
Jagadish Jagz 
Fahad-AkhtarFahad-Akhtar
Hi Jagadish ,
You can do a SOQL query to using for all KeySet and Values in your map to get all the user with the roles that you have and create a map with Role id as key and user id as value, so you can get the user id using roleid directly, this should solve your problem.

Thanks,
Fahad Akhtar
Salesforce BlitzSalesforce Blitz
Hi Fahad..


I have a user Id.  I want to fetch the users below him, only the ones who report to him(only 1 level deep).

Not multiple levels deep.

parentrole id works only on userrole..i guess,,


how to achieve dis?