Thursday, June 21, 2012

To send Email from Apex using email Template

To use an Email Template from Apex Class in order to send an email:
In order to send an email from apex class, you can use any of the below messaging objects.
Single Email Messaging :
Instantiates the object to send single email message.
Ex: To send single email to a selected Contact.
public void SendEmail()
{
contact con=[Select id from contact limit 1];
EmailTemplate et=[Select id from EmailTemplate where name=:'EmailTemplatename'];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(con.Id);
mail.setSenderDisplayName('Charan Tej');
mail.setTemplateId(et.id);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
For other object methods of Single Email Messaging, Click Here
Note: Do remember that we can send only 10 emails in method invocation of Apex class using SingleEmailMessage.
Mass Email Messaging:

Instantiates the object to send mass email message.
Ex: To send mass email to a Contacts.

public void SendEmail()
{
List<contact> lstcon=[Select id from contact limit 200];
List<Id> lstids= new List<Id>();
for(Contact c:lstcon){
lstids.add(c.id);
}
EmailTemplate et=[Select id from EmailTemplate where name=:'EmailTemplatename'];
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
mail.setTargetObjectIds(lstIds);
mail.setSenderDisplayName('Charan Tej');
mail.setTemplateId(et.id);
Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}

For other object methods of Mass Email Messaging, Click Here

No comments:

Post a Comment