5

I have tried this to send mail to the logged in user

String[] toAddresses = new String[] {UserInfo.getUserEmail()};
mail.setToAddresses(toAddresses);

This works fine for the users who have logged in, but I would like to send mail only to System Administrator.

Thanks in advance.

  • You mean send mail only if the user is System Administrator? – Santanu Halder Jan 20 '16 at 8:29
  • Whoever logs in I want the mail to be send mail to the system admin irrespective of whoever the user be.@SantanuHalder – DOMINIC EDWARD Jan 20 '16 at 8:33
  • 1
    than query users with System Admin profile and use their email. like - Profile p = [SELECT id FROM Profile WHERE name = 'System Administrator']; Users[] u_to_send = [SELECT Id, Email FROM User WHERE ProfileId = :p.Id]; String[] toAddresses = new String[] {u_to_send.get(0).Email}; mail.setToAddresses(toAddresses); but I would recommend to use setTargetid of user to avoid limit of sending direct emails to addresses – kurunve Jan 20 '16 at 8:42
  • it worked fine @kurunve. Thanks. Can you post this as answer – DOMINIC EDWARD Jan 20 '16 at 9:07
5

Basic idea would be to query user that you need (f.e. with system admin profile etc), and use email on that field. For example:

Profile sys_adm_profile = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
List<User> sys_adm = [SELECT id, Email FROM User WHERE ProfileId = :sys_adm_profile];
String[] toAddresses = new String[] {sys_adm.Email};
mail.setToAddresses(toAddresses);

There is better approach -- as well as email is being send to user, then mailsetTargetObjectId(userId) should be used to avoid limits of email that can be send for different email addresses. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm#email_limits_section

Also those method of getting system admin profile is not perfect -- it would fail in orgs with non english language.

4

You can do it with just one query:

SELECT Email FROM User WHERE Profile.Name = 'System Administrator'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.