Here is to code to send email using salesforce apex when new contact record is get created.
List emailList = new List();
Messaging.SingleEmailMessage emailTemplate = new Messaging.SingleEmailMessage();
List lstNewContact = [Select Name, Email From Contact where Id =: Trigger.new ];
for(Contact contact : lstNewContact) {
emailTemplate.setToAddresses(new String[] {contact.Email});
emailTemplate.setSubject('New contact record created');
emailTemplate.setHtmlBody('Hello team, new contact is added Name: '+ contact.Name);
emailList.add(emailTemplate);
Messaging.sendEmail(emailList );
}
}
We have explained the same in this video.
How the code is meant to work
The code sits in an after insert trigger on Contact. It loads the new Contacts, builds an email for each one with Messaging.SingleEmailMessage, and sends the emails with Messaging.sendEmail.
Problems in this version
- One email object is reused. The message is created once outside the loop and added to the list on every pass. Every list entry points to the same object, so all emails end up with the last recipient.
- sendEmail runs inside the loop. The growing list is sent again on each pass, and Apex allows only 10 sendEmail calls per transaction.
- The query uses = instead of IN.
Where Id = :Trigger.newmust beWhere Id IN :Trigger.new. The query is also not needed, because the fields are already inTrigger.new.
Corrected trigger
trigger ContactTrigger on Contact (after insert) {
List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
for (Contact con : Trigger.new) {
if (String.isBlank(con.Email)) {
continue;
}
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new List<String>{ con.Email });
mail.setSubject('New contact record created');
mail.setHtmlBody('Hello team, a new contact was added. Name: ' + con.FirstName + ' ' + con.LastName);
emails.add(mail);
}
if (!emails.isEmpty()) {
Messaging.sendEmail(emails);
}
} Each Contact gets its own message, and one sendEmail call sends them all. The Name field is not reliable in trigger context, so the message uses FirstName and LastName.
Points to note
- The code emails the Contact. If you want to notify your team, replace the address with a team address, kept in a custom label or custom metadata.
- Daily limits apply to emails sent from Apex, so avoid emails for routine changes.
- For simple cases, a record-triggered Flow with an email alert needs no code.
FAQ
Do emails sent from a test class go out?
No. Tests count the call but do not deliver the email.
Can I use an email template?
Yes. Use setTemplateId together with setTargetObjectId.