Sending Email Template via APEX – No TargetObjectId?

kitty-help-fix-computerHere’s a quick tip!

If you’re using APEX to send an email template to a group of addresses but don’t necessarily have a User, Contact, or Lead to associate the email to (setTargetObjectId) normally you’re out of luck right?

Not necessarily – insert a little dark magic…literally!   We’re going to insert a Contact (or Lead) in our APEX code with an email address of “”, use that for our SingleEmailMessage, then delete it when we’re done.


Now – you want to always do a sanity check before slamming code like this in.  Make sure that you properly fit it in your org and ensure that you aren’t going to bump into any other triggers, validation rules, etc, etc, etc when you’re inserting this “dummy contact”.  This code is NOT necessarily best practice as-is, it’s here just to help you realize your own best-practice method.  =)

// Create Contact
Contact con = new Contact();
con.FirstName = 'Test';
con.LastName = 'Contact';
con.Email = '';
insert con;
// Create Email and Send
Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
msg.setTemplateId('Your Email Template Id');
msg.setCcAddresses(new String[] {'', ''});
msg.setWhatId('Your Record Id if applicable');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });
// Don't Forget!  Clean up!
delete con;

Happy coding!