Apex Code Tip – Sending Email to Salesforce Users

Email with WarningApex allows you send emails from code using the Messaging namespace. As usual Salesforce governor limits are at work and you could unwittingly hit your limits without needing to.

If you are sending email to users within your organisation, make sure you send the email to a User not an email address. Emails to Users are not included in this limit.

By way of example, consider a batch job that notifies the user submitting the job whether the job succeeded or failed:

Avoid using an Email Address for a Salesforce user.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] { UserInfo.getUserEmail() });
mail.setSubject('Batch Job Status Report');
mail.setPlainTextBody('The job completed successfully. Have an A1 day!');

Use the Target Object Id to reference the Salesforce User.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSubject('Batch Job Status Report');
mail.setPlainTextBody('The job completed successfully. Have an A1 day!');

Note, you need to use: setSaveAsActivity(false) when using a target object Id as the default value is true.

Remember you can get a User Id from the CreatedBy, LastModifiedBy or OwnerId fields on an object. However, be aware that the OwnerId could instead be a Queue.

More Info:

Email Governor Limits.

Messaging Namespace.


Author, brainstormer, coder, dad, explorer, four chord trickster, gig goer, home worker, inquisitor, joker, knowledge seeker, likes: marmite, note scribbler, opinionator, poet, quite likes converse, roller skater, six music listener, tea drinker, urban dweller, vinyl spinner, word wrangler, x-factor hater, Yorkshireman (honorary), zombie slayer (lie).

Tagged with: , , ,
Posted in apex, code, force.com, salesforce
About Me
Product Services Developer at:
All views expressed here are my own. More about me and contact details here.
Please sponsor me …
My wife and I are running the Great North Run to support The Nick Alexander Memorial Trust

If you've found my blog useful, please consider sponsoring us. Sponsor me on BT MyDonate

Enter your email address to follow this blog and receive notifications of new posts by email.

Copyright (there isn’t any, feel free to reuse!)

To the extent possible under law, Tony Scott has waived all copyright and related or neighboring rights to MeltedWires.com Examples and Code Samples. This work is published from: United Kingdom.

%d bloggers like this: