How can I configure Salesforce to send an email to a user when its user in the system is activated (IsActive = true
)?
Right now I can create a workflow rule that triggers when the User record is changed, and specify to run when the IsActive
field is set to true, but when I try to create the Email Alert, I don't see a way to inform that I want the email to be sent to that user.
I only get these options:
But none of them seem to fit. I tried using the 'Email Field' one, but it doesn't work.
Since I tried this, I thought of doing it with a trigger too, but when I send the notification email, the email simply does not arrive at my inbox. No errors are thrown, the Deliverability is ok, and the code works when I run it from the console.
I'm calling this method in an afterUpdate trigger on User:
public void notifyUser() {
EmailUtils email_utils = new EmailUtils();
EmailTemplate template = [SELECT Id, DeveloperName FROM EmailTemplate WHERE DeveloperName = 'UsuarioAtivado' LIMIT 1];
Map<Id, User> oldmap = (Map<Id, User>) Trigger.oldMap;
List<Id> activated_users_ids = new List<Id>();
for (User u : (List<User>) Trigger.new) {
if (oldMap.containsKey(u.Id) && !oldMap.get(u.Id).IsActive && u.IsActive) {
System.debug('User activated. [' + u.Id + ']');
activated_users_ids.add(u.Id);
}
}
List<User> usuarios_ativados = [SELECT Id, Name, Email FROM User WHERE Id IN :activated_users_ids];
Messaging.reserveSingleEmailCapacity(usuarios_ativados.size());
List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
for (User u : usuarios_ativados) {
Messaging.SingleEmailMessage sem = new Messaging.SingleEmailMessage();
sem.setTemplateId(template.Id);
sem.setSaveAsActivity(false);
sem.setOrgWideEmailAddressId(email_utils.addresses.get('CompanyName'));
sem.setTargetObjectId(u.Id);
emails.add(sem);
System.debug('Email:');
System.debug(sem);
}
Messaging.sendEmail(emails);
}
System.debug(Messaging.sendEmail(emails));
instead ofMessaging.sendEmail(emails);
to check the results. And after that look into debug logs - it could be that your trigger doesn't fire the code.isSuccess()
returns true).