User Story
As a sales representative for XYZ Company, I want to ensure that an email is automatically sent to the email address populated on a new Contact record, using a specified email template. This will help me establish communication with the Contact and provide them with important information about our products and services.
The email should be triggered as soon as a new Contact record is created, and it should use the designated email template. The email should be sent to the email address populated on the Contact record.
Code
trigger ContactTrigger on Contact (after insert) {
List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>();
String templateName = 'Contact Creation Notification'; // Replace with your email template name
EmailTemplate emailTemplate = [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Name = :templateName LIMIT 1];
for (Contact con : Trigger.new) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new List<String>{con.Email});
email.setSubject(emailTemplate.Subject);
email.setHtmlBody(emailTemplate.HtmlValue.replace('{!Contact.FirstName}', con.FirstName));
emailList.add(email);
}
Messaging.sendEmail(emailList);
}