Thursday 3 October 2013

Send Email Using Trigger

Here I am using Trigger to send an email to the Contact, which don't have any associated Account.

There is a singleEmailMessage & MassEmailMessageclasses are provided by the Salesforce, which we can use to send an email or email in bulk to the users.

First of all we need to create a Helper class,we will call this class using Trigger, whenever the condition met, the trigger will call this Helper class, and all the stuffs whatever we are doing, will be in helper class. We are using an email template too.

This is an small an easy to understand Example.

Here is the Helper class named "HelperContactTrigger"

/**
* Description : Trigger to send email to the contact if accountId is null .
*
* Created By : Abhi Tripathi
*
* Created Date : 07/16/2013
*
* Revision Logs : V1.0
*
**/
public with sharing class HelperContactTrigger {

//static method
public static List sendEmail(List contacts) {

//query on template object
EmailTemplate et=[Select id from EmailTemplate where name=:'Sales: New Customer Email'];

//list of emails
List emails = new List();

//loop
for(Contact con : contacts){

//check for Account
if(con.AccountId == null && con.Email != null){

//initiallize messaging method
Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

//set object Id
singleMail.setTargetObjectId(con.Id);

//set template Id
singleMail.setTemplateId(et.Id);

//flag to false to stop inserting activity history
singleMail.setSaveAsActivity(false);

//add to the list emails
emails.add(singleMail);
}
}

//send mail
Messaging.sendEmail(emails);

return contacts;
}
}

Now we will call the above class in our trigger named "SendEmailToAccount"
Here is the trigger, just paste this in your Account's Trigger

Trigger SendEmailToAccount on Contact (after insert, after update) {

if(Trigger.isAfter){
if(Trigger.isInsert || Trigger.isUpdate){

//helper class for single email but bulk messages
HelperContactTrigger.sendEmail(trigger.new);
}
}
}


Now you just need to create a Contact record and fill the Email field with your email and save it.
You will receive an email from the your salesforce.

2 comments: