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
programmer4hireprogrammer4hire 

Sending an email when a user hasn't logged in for 30 days

We would like to send a notification email to a user if they haven't logged in the past 30 days.  The email would say something like please log in or else their account will be disabled.  Since we can't do this via workflow, is this doable with Apex?
Guyver118Guyver118

Yes you can. Here is the plan to make it work.

 

1)Download the cron kit from appexchange and study it, test a quick batch run.

 

2)Using the cron kit batch a trigger that runs every week to check all users that are active.

 

3)In this case the batch runs your trigger that queries all active users and checks the days between the lastlogindate and the batch run date.

 

 

Possible code:

 

 

public class CheckActiveUsers_v1 { private List<User> userList; private Set<Id> emailList; CheckActiveUsers_v1() { userList = new List<User>([SELECT Id, LastLoginDate, IsActive FROM User WHERE IsActive = TRUE]); emailList = new Set<Id>(); } private void FindAllInActiveUsers() { Date checkDate = Date.Today(); for(User a : userList) { if(a.LastLoginDate.daysBetween(checkDate)<30)) { emailList.add(a); } } } public void EmailInActiveUsers() { FindAllInActiveUsers(); if(!emailList.isEmpty()) { Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage(); mail.setTemplateId('ID OF INACTIVE USER EMAIL TEMPLATE'); mail.setTargetObjectIds(emailList); Messaging.sendEmail(new Messaging.MassEmailMessage[] {mail }); } } }