SENDING AN EMAIL FROM YOUR APEX CLASS | Techila
2086
single,single-post,postid-2086,single-format-standard,ajax_updown_fade,page_not_loaded,,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,qode-content-sidebar-responsive,qode-theme-ver-9.4.2,bridge,wpb-js-composer js-comp-ver-4.12,vc_responsive
 

SENDING AN EMAIL FROM YOUR APEX CLASS

SENDING AN EMAIL FROM YOUR APEX CLASS

SENDING AN EMAIL FROM YOUR 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 an Apex Class.

Sending an email from an 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.

Step 1:

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 below

SENDING AN EMAIL FROM YOUR APEX CLASS

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 yours.

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

Template ID

Do you think it’s 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 an Email Template but you don’t have a Contact, or User, or Lead?

There may and will arise situations in which you have an 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.

Courtesy: http://www.forcetree.com/2009/07/sending-email-from-your-apex-class.html
http://lh3.googleusercontent.com/–a4Wd4NANa8/VcwmbLfE7-I/AAAAAAAAA4Q/-Jq6CLpGIQg/image_thumb%25255B3%25255D.png?imgmax=800

“Know more about Salesforce Consulting at Techila”

Author: techila

No Comments

Post A Comment