[SalesForce] Sending Email from apex controller by calling an email template

I have an email template which I am calling it from a work flow rule. Also I have a check box in contact object, when I click on check box the email template will send email to the contact email address. Its working fine.

But I want to know how we can implement controller side. I mean a have a page where I am entering contact details(with email id), when I click on Save i am able to save the record and those records I am displaying in a different table of same page. So from the second table, I will select one contact and when I will click on button(something called send email) in that page, it should send an email to selected to contact.

I am just looking for the logic on how to call an email template from controller and send email to selected record.

Best Answer

This is a very simple piece of code

EmailTemplate templateId = [Select id from EmailTemplate where name = 'Your template Name'];
List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateID(templateId.Id); 
mail.setTargetObjectId(contactId)
mail.setSaveAsActivity(false);
allmsg.add(mail);
Messaging.sendEmail(allmsg,false);

Use this piece of code to send email from apex using template.

Update: Or you can create a utility class as suggested by @cropredy. You can find reference here.

Related Topic