global class LastLoginEmailJObs implements Schedulable {
global void execute(SchedulableContext SC) {
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for(User u : [SELECT Id, LastLoginDate, Email FROM User]) { //You can add filter for active users only
If( u.LastLoginDate <= System.today().addDays(-1)){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new List<String> { u.Email });
mail.setTargetObjectId('User ID');
mail.setSenderDisplayName('Salesforce Support');
mail.setUseSignature(false);
mail.setBccSender(false);
mail.setSaveAsActivity(false);
EmailTemplate et = [Select Id from EmailTemplate where Name = 'Users_Please_login'];
mail.setTemplateId(et.Id);
mails.add(mail);
}
}
Messaging.SendEmailResult [] r = Messaging.sendEmail(mails);
}
}
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.– Community BotCommented Oct 13, 2022 at 11:14
-
Please do not ask the SFSE community to write code on your behalf - check out help center for more guidelines, and learn about How to Ask to get the most out of this community.– David ReedCommented Oct 13, 2022 at 15:39
Add a comment
|
1 Answer
Before writing a unit test, you need to fix your code. See the comments below.
global class LastLoginEmailJobs implements Schedulable {
global void execute(SchedulableContext SC) {
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
// Don't query in a loop; we'll move it here.
EmailTemplate et = [Select Id from EmailTemplate where Name = 'Users_Please_login'];
// Use a filter instead of the if statement for performance reasons.
for(User u : [SELECT Id FROM User WHERE (LastLoginDate < LAST_N_DAYS:1 OR LastLoginDate = NULL) AND IsActive = true]) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Don't use toAddresses to email users, as this is rate limited daily.
// mail.setToAddresses(new List<String> { u.Email });
mail.setTargetObjectId(u.Id);
mail.setSenderDisplayName('Salesforce Support');
mail.setUseSignature(false);
mail.setBccSender(false);
mail.setSaveAsActivity(false);
mail.setTemplateId(et.Id);
mails.add(mail);
}
Messaging.SendEmailResult [] r = Messaging.sendEmail(mails);
}
}
Aside from that, we add a filter to check for LastLoginDate over a day ago, or that have never logged in. Here's the trick; we're going to just create a new User, then run the class:
User u = new User(); // fill in all required details here
insert u;
Test.startTest();
System.scheduleJob('Testing Job', '0 0 * * * ?', new LastLoginEmailJobs());
Test.stopTest();