Saturday, November 5, 2011

Send Email (Single and Mass Email)Through Apex Class

There may be situations in which you would not want a workflow email alert, because either your criteria to send an email may be too complex or the person whom you want to send an email has to be determined dynamically..... In such situations you can choose to send an email from a Apex Class...

Sending an email from a Apex Class is so easy... Basically there are two categories

SingleEmailMessage - This is used when you want to send an email to a single person..

MassEmailMessage - This is used when you want to send an email to a group...

First, let us see about the SingleEmailMessage type....

Step1:

Create a Apex Class with the following code....


public class testemail
{
private final Contact con;
public testemail(ApexPages.StandardController controller)
{
this.con=(Contact)controller.getRecord();
}

public void SendEmail()
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(con.Id);
mail.setTemplateId('00X90000000QHUD');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

Mention a valid Email Template ID in the colored part...

Step 2:

Create a VF page named as "testemail" or anything as your wish , and paste the code below..


<apex:page standardcontroller="Contact" extensions="testemail">
<apex:form>
<apex:commandButton value="Send Email!" action="{!SendEmail}"/>
</apex:form>
</apex:page>


Step 3:

Go to the url bar and type
https://yoursalesforceinstance.com/apx/testemail?id=00390000001TqnV

Note that i have mentioned a valid Contact Id of my organization, make sure you mention a valid contact ID of your SF instance.

Step 4:

You should be able to view the page  with a button Send Email



Click on the "Send Email" button and your email is sent to the Email address of the Contact mentioned in the url.....

Analyzing the code.. we can see that four simple lines are enough to send a mail

The first line instantiates an instance of the SingleEmailMessage object...

The second line associates the Contact ID to the email.. this is used to retrieve the toaddress and any merge fields that may be included in your email template...

Note that in the third line we have hardcoded the Email Template ID... This ID belongs to my organization, you will have to replace it with your's...

And in the final step the sendemail method is called and the email is sent...

Template ID

Do you think its weird to hardcode a Template Id in your code.. yes, definitely it is..

There is a EmailTemplate object which you can query and retrieve the template ID you require... below is a small sample which you can plug-in into this example after modifying appropriately..
emailtemplatelist = new List<EmailTemplate>();
for ( EmailTemplate e : [select Id,Name,Subject,body from EmailTemplate where name like :userinputtemplatename+'%'])
{
emailtemplatelist.add(e);
}  

Sending an email without a Template -

The above method is used only when you want to associate a Email Template to your email. When you use an Email Template you will have to specify a valid Contact Id, or User Id, or Lead Id as the target Object Id. If you specify any other object's Id your code wouldn't work.

If you do not want to use a template you can specify the toAddress, Subject and Body of the email using the appropriate methods. Below is a piece of code which sends an email not associated to an email template.

 String[] toaddress = new String[]{};
toaddress.add(emailaddress[i]);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(toaddress);
mail.setsubject(subject);



Hope the methods are self-explanatory...


You have a Email Template but you dont have a Contact,or User,or Lead ????????

There may and will arise situations in which you have a Email Template.. You would not have any merge fields in this Email Template. ..

You would like to send an Email using this Email Template.. But you do not have a Contact, or a Lead or a User to set as the targtObjectId...

In such cases, you can create a Contact on the fly, send the email and then delete the Contact... Remember to create the contact with Name, and Email since these are mandatory fields to send an Email...


Sending Mass Email


Now that you have learnt to use the single email message, the mass email message is much simpler to understand...

You just need to replace the targetobjectId with setTargetObjectIds... And of course, you will have to specify a list of valid Contact,User or Lead ID's...

For the same example, just replace the Apex code as below...

public class testemail
{
  private final List<Id> contactids;
  public List<Contact> con;
  public testemail(ApexPages.StandardController controller)
  {
     con = [select Id from Contact limit 250 ];
     for(Integer i=0;i<250;i++)
     {
         contactids.add(con[i].Id);
      }  
  }

  public void SendEmail()
  {
       Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
       mail.setTargetObjectIds(contactids);
       mail.setTemplateId('00X90000000QHUD');
       Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
  }  


}

What we do is, query the contact object and get a list of Contact Id's... We then set this list of ID's as the targetobjectId's....


 Sending Mass Email Limit
 See “Guidelines on Sending Mass Email” in the Salesforce online help.

Tuesday, November 1, 2011

How to set Debug Log for Apex Class and Force.com Site

In sales force it is very easy to log and track the apex program. To log the apex code use below line of code:

        System.debug(“Your message”);
Lets assume you have written below line of code in one of the controller extension’s constructor :
   
    System.debug('\n\nI Am In the constructor of Apex class \n\n');

When you are setting debug for internal Apex execution:

1- Enable the log for particular user who is going to execute that code. Go to “Setup | Administration Setup | Monitoring | Debug Logs“.

2- To enable the log for this user click on new button .

3- Select the user and save.

4- Now execute that Visualforce page for which controller code is written.

5- After execution again go to the Debug Logs page, where the user is added. You will see the screen like below

    As you can see now that new row is added in “Debug Logs” section. click on the “view” button.
    Debug statement printed in debug logs.

When you are setting debug for external Force.com site execution:

Steps 1,2 are same.

3-  Select Site User and save

Steps 4,5 are same

N.B. How to see site user:   App SetUp ->Create ->Site ->Click on Site Lebel ->Click Public Access Settings ->Click View users button.


For more information on log levels, see “Setting Debug Log Filters” in the Salesforce online help.