Here is the simplest code to send emails to contact when email id is not blank:
// Send a business proposal to each new Contact
trigger Proposal on Contact (before insert) {
// Step 0: Create a master list to hold the emails we'll send
List<Messaging.SingleEmailMessage> mails =
new List<Messaging.SingleEmailMessage>();
for (Contact myContact : Trigger.new) {
if (myContact.Email != null && myContact.FirstName != null) {
// Step 1: Create a new Email
Messaging.SingleEmailMessage mail =
new Messaging.SingleEmailMessage();
// Step 2: Set list of people who should get the email
List<String> sendTo = new List<String>();
sendTo.add(myContact.Email);
mail.setToAddresses(sendTo);
// Step 3: Set who the email is sent from
mail.setReplyTo('sirdavid@bankofnigeria.com');
mail.setSenderDisplayName('Official Bank of Nigeria');
// (Optional) Set list of people who should be CC'ed
List<String> ccTo = new List<String>();
ccTo.add('business@bankofnigeria.com');
mail.setCcAddresses(ccTo);
// Step 4. Set email contents - you can use variables!
mail.setSubject('URGENT BUSINESS PROPOSAL');
String body = 'Dear ' + myContact.FirstName + ', ';
body += 'I confess this will come as a surprise to you.';
body += 'I am John Alliston CEO of the Bank of Nigeria.';
body += 'I write to request your cooperation in this ';
body += 'urgent matter as I need a foreign partner ';
body += 'in the assistance of transferring $47,110,000 ';
body += 'to a US bank account. Please respond with ';
body += 'your bank account # so I may deposit these funds.';
mail.setHtmlBody(body);
// Step 5. Add your email to the master list
mails.add(mail);
}
}
// Step 6: Send all emails in the master list
Messaging.sendEmail(mails);
}
salesforce supports two type of emails single and mass email.
SingleEmailMessage
Instantiates an email object used for sending a single email message. The syntax is:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
Simple example
trigger trgSendMailOnLead on Lead (before insert) {
Map<String,String> mapZipForEmail = new Map<String,String>();
Postal code from Lead object and Zip code from Zip_code__c
for(Zip_code__c thisZipCode : [Select id, zipCode__c,assigned_user__c from Zip_code__c ]){
mapZipForEmail.put(thisZipCode.zipCode__c, thisZipCode.assigned_user__c)
}
// Create a master list to hold the emails
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for (Lead myLead : Trigger.new) {
if(mapZipForEmail.containsKey(myLead.PostalCode__c)){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// list of people who should get the email
List<String> sendTo = new List<String>();
sendTo.add(mapZipForEmail.get(myLead.PostalCode__c));
mail.setToAddresses(sendTo);
// Set email is sent from
mail.setReplyTo('youremail@yourdomain.com');
mail.setSenderDisplayName('Your Name');
// Set email contents
mail.setSubject('URGENT BUSINESS PROPOSAL');
String body = 'Dear ' + myLead.FirstName + ', ';
body += 'Email Body.';
mail.setHtmlBody(body);
// Add your email to the master list
mails.add(mail);
}
}
// Send all emails in the master list
if(mails.size()>0) Messaging.sendEmail(mails);
}
Instantiates an email object used for sending a mass email message. The syntax is:
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
trigger leaveType on Leave_Type__c (after insert) {
Id[] targetObjectIds = new Id[] {};
Id[] whatIds = new Id[] {};
final String template = 'EmailDemoSendMassTemplate';
Messaging.MassEmailMessage message = new Messaging.MassEmailMessage();
message.setTemplateId([select Id from EmailTemplate where Name = :template].Id);
Map<Id,Employee__c> allEmployees = new Map<Id,Employee__c>([SELECT Id FROM Employee__c LIMIT 50000]);
Contact[] contacts = [select Id from Contact where Employee__c IN:allEmployees.keyset()];
for (Contact c : contacts) {
targetObjectIds.add(c.Id);
}
message.setTargetObjectIds(targetObjectIds);
Messaging.sendEmail(new Messaging.Email[] {message});
}
EmailTemplate template = [SELECT Id, Name FROM EmailTemplate WHERE DeveloperName = 'YOUR TEMPLATE' LIMIT 1];
Messaging.MassEmailMessage emails=new Messaging.MassEmailMessage();
// Can be user or contact or lead
emails.setTargetObjectIds(UserIds);
// EMail Template ID
emails.setTemplateId(template.Id);
//data for merge fields
emails.setTargetObjectIds(targetObjectIds);
emails.saveAsActivity = false;
Messaging.SendEmail(New Messaging.MassEmailMessage[]{emails});
Please run this code it is simple and easy for new salesforce developer.
Example->Write a trigger on Contact whenever a contact inserted, then send an email to the email field and the owner and the contact with the subject line "Alert [Conatct]" and with the message 'A new contact is inserted in Salesforce and the Full name of the contact, phone and address fields."
//Helper Class //
public class ContInsertSendEmailOwner {
public static void senEmail(List<Contact> conList){
Set<Id> setConIds = new Set<Id>();
for(Contact cont:conList){
setConIds.add(cont.Id);
}
List<Contact> contList = new List<Contact>();
contList = [Select email,Owner.Email ,OwnerId,Phone,Name,MailingAddress from Contact where Id IN:setConIds];
for(Contact c :contList){
List<String> conEmail = new List<String>();
// System.debug('email'+userEmail);
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
conEmail.add(c.Email);
conEmail.add(c.Owner.Email);
mail.setToAddresses(conEmail);
System.debug('emailll.........>'+mail);
mail.setReplyTo('mohd@ca.com');
mail.setSenderDisplayName('Mohd rais');
mail.setSubject('Alert '+c.Name);
String body ='<table border ="1" style ="border-collapse"><caption>A new Contact is inserted in Salesforce.</caption><tr><th> Full Name</th><th>Phone</th><th>Address</th></tr>';
body+= '<tr><td>' + c.Name +'</td><td>'+c.Phone+'</td><td>'+c.MailingAddress+'</td></tr>';
body+='</table>';
mail.setHtmlBody(body);
mails.add(mail);
try{
Messaging.sendEmail(mails);
}catch(DMLException e){
System.debug('There is erros'+e.getMessage());
}
}
}
}
//Trigger Class//
trigger ContInsertSendEmailOwnerTrigger on Contact (after insert) {
if(Trigger.isAfter){
if(Trigger.isInsert){
ContInsertSendEmailOwner.senEmail(Trigger.New);
}
}
}
Please mark it as best Answer if you find it helpful.
Mark answer as best if you got your solution.
SingleEmailMessage
Instantiates an email object used for sending a single email message. The syntax is: Simple example
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm#apex_classes_outbound_single
http://www.sfdc99.com/2014/03/01/sending-emails-using-apex/
Mass EMail
Instantiates an email object used for sending a mass email message. The syntax is:
Please run this code it is simple and easy for new salesforce developer.
Example->Write a trigger on Contact whenever a contact inserted, then send an email to the email field and the owner and
the contact with the subject line "Alert [Conatct]"
and with the message 'A new contact is inserted in Salesforce and the Full name of the contact, phone and address fields."
Please mark it as best Answer if you find it helpful.
Thank You
Ajay Dubedi