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
Luffy Carl_opLuffy Carl_op 

How to send email with object fields?

Now, I seted up a system, for users login and logout every. I want to add one function that System checks records everyday, if anyone didn't logged, send a email to him.I have use the schedule apex class find exceptional users,got their ID, BUT i don't know how to write the email body. I want to show some user's info in this email, just like Hello, Luffy. But it's invalid. Please help me.Thanks.
//Here i get the list of exception users. 
List<User> lu = new List<User>();
        lu = [select Id, Name, Email
             (SELECT Name, BeginTime__c, EndTime__c From WorkTime__r
             )  From User
        ];
        //Judge if the list is null,if user don't login , add to list
        List<Id> em = new List<String>();
        for(User u : lu){
            if( [select Name, BeginTime__c, EndTime__c, WorkerRef__c From WorkTime__c
                    Where WorkerRef__c =:u.id
                    And DAY_ONLY(BeginTime__c) =: Date.Today()
                    ].isEmpty() ){
                em.add(u.Id);
           }
        }
//In this template, it's both invalid that using WorkTime__c's fields or User's fields
        String dn =  'System_Exception_Records';
        Id tid;
        tid = [select id from EmailTemplate where developername =:dn ].id;   
           
        for(Id saddr : em){
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setTargetObjectId(saddr);
            email.setTemplateId(tid);
            email.setSaveAsActivity(false);
            Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
        }

 
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi Luffy Carl_op ,

Please try below code.
//Here i get the list of exception users. 
List<User> lu = new List<User>(SELECT Id,LastLoginDate FROM User);
       
        //Judge if the list is null,if user don't login , add to list
        List<Id> em = new List<String>();
        for(User u : lu){
            if(u.LastLoginDate.addHours(24)<Date.now()){
                em.add(u.Id);
           }
        }
//In this template, it's both invalid that using WorkTime__c's fields or User's fields
        String dn =  'System_Exception_Records';
        Id tid;
        tid = [select id from EmailTemplate where developername =:dn ].id;   
           
        for(Id saddr : em){
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setTargetObjectId(saddr);
            email.setTemplateId(tid);
            email.setSaveAsActivity(false);
            Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
        }

Let us know if it helps you.