[SalesForce] Email Owner of New Lead inserted through Apex

I am using Apex code (similar to what is shown here) to create new Leads. What is the best way to automatically trigger an email to be sent to the lead Owner when it is created (similar to what would be sent if I assigned the lead to someone in the web interface and clicked on the checkbox to Send Notification Email)?

I am using Professional edition, with Workflows added on.

Best Answer

Config solution would be to create a simple workflow rule with

  • condition = "every time a new record is created" (+ anything you have to distinguish the records like LeadSource = 'API' maybe?)
  • email alert to the owner (you'd have to prepare an email template first)

Apex version could be to set a Task for the Owner with optional Email notification. Insert your Leads first, then for each create a list of Tasks with ParentId = lead.id and OwnerId = lead.OwnerId. The important part would be to not go with straightforward

insert tasks;

but use the DML Options

Database.DMLOptions dlo = new Database.DMLOptions();
dlo.EmailHeader.triggerUserEmail = true;
Database.insert(tasks, dlo);

I think the config version is cleaner (easier to maintain in future if you need to change the criteria or temporarily disable it).


You might also want to look into the Chatter Actions and Lead assignment rules (but assignment rules let you specify the notification only if you change the owner in same rule so potentially you'll need to move more logic from Apex to config before you can use it. And you'd still need to make an email template).