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 “no-reply@organization.com”, use that for our SingleEmailMessage, then delete it when we’re done.

DISCLAIMER!

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 = 'no-reply@organization.com';
insert con;
// Create Email and Send
Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
msg.setTemplateId('Your Email Template Id');
msg.setCcAddresses(new String[] {'email1@recipient.com', 'email2@recipient.com'});
msg.setTargetObjectId(con.Id);
msg.setWhatId('Your Record Id if applicable');
msg.setSaveAsActivity(false);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });
// Don't Forget!  Clean up!
delete con;

Happy coding!