Sending an Email from your Apex Class

1:23 AM

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 below



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

44 comments

  1. The mass email is working for Contact but it is not working for User. As per the defination it should work for Contact, lead and User objects.

    ReplyDelete
    Replies
    1. hi am gettting error like

      System.NullPointerException: Attempt to de-reference a null object
      Class.testemail.: line 10, column 1



      page code:









      class


      public class testemail
      {
      private final List contactids;
      public List con;
      public testemail(ApexPages.StandardController controller)
      {
      con = [SELECT Id FROM Contact limit 25 ];
      for(Integer i=1;i<25;i++)
      {
      contactids.add(con[i].Id); //line 10, column1
      }
      }

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


      }

      Delete
    2. hi.,
      i'm also getting same error
      did you find answer??

      Delete
  2. hey guys this is an excellent code. I am working on something similar, will show u an updated code soon.

    ReplyDelete
  3. Wow, good code. My initial thoughts were that this was only possible through email templates and Salesforce objects. This is a feature they should be promoting more in the documentation.

    ReplyDelete
  4. hi this is gopi if above is good but i have a EmailTemplates in S-Controles then i add this emailTemplate to a CustomField in A custom object can u check this is it possible
    for Ex: A__c --Custom object in this we have a field body__c --Rich Text in this we have a template , how we add this template date to that field ......

    ReplyDelete
  5. Thanks for posting this code.

    ReplyDelete
  6. Thank u very much for the codes. but i have a problem actually. I am using an email template,and my emal template has the recipient type = user and the relatedTo = task.in my code i can specify the recipienttype with mail.setTargetObjectIds ,but how can i specify the relatedTo ????

    ReplyDelete
  7. I,ve got my answer to my question from the force.com forum.The answer is to use the whatId.
    that's all.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. I have merged fields(of Idea Object) in my email template and i want send mass email to all users who have commented on idea.

    ReplyDelete
  10. hi........ this is prakash, i'm new to salesforce. i don't know how to get the valid Contact Id of my organization. ..... plz suggest me...

    ReplyDelete
    Replies
    1. contacts tab-> press on any link of contact you got -> go to url ,there you will find a contact id starting with 00.........(15).

      Delete
  11. Go to the "Contacts" tab, click on any contact. It will show you the detail page for the contact with all relevant contact information. Note the URL .. It would be something like https://cs3.salesforce.com/003Q000000MUc9M ... Now 003Q000000MUc9M is your Contact ID

    ReplyDelete
  12. How the above code need to send at Scheduled Time..?

    ReplyDelete
  13. subject :- Salesforce administrator

    Salesforce Consultant & Salesforce administrator can help you with salesforce projects and salesforce certification, salesforce helpdesk, salesforce training, salesforce automation helps in salesforce

    http://www.plug2salesforce.com

    ReplyDelete
  14. @Gopi

    It is required to use Schedule apex for this kind of requirement .

    Thanks,
    Mayank Joshi

    ReplyDelete
  15. What if I need to forward an email that is already in salesforce. It is stored as a task.

    ReplyDelete
  16. Same Question as above. What if I need to forward an email that is already in salesforce. It is stored as a task.

    ReplyDelete
  17. How are you supposed to do it if your merge fields are not from a User Contact or Lead?
    Useing email.setTargetObjectId sure doesn't work if the merge fields come from the quote.

    ReplyDelete
  18. There is no "setTargetObjectIds" only "setTargetObjectId", then how to send Mass Email?

    ReplyDelete
  19. Can you publish the code for a mass email with template not related to a contact?!

    Thanks

    ReplyDelete
  20. HI,
    I have a doubt that how you select records for MassEmail and can we have a list button to select multiple records

    ReplyDelete
  21. Hi thanks a lot for a discerning post, I really found your blog by mistake while searching on Google for something else closely related..I have bookmarked your site..
    mass email service india

    ReplyDelete
  22. hi am gettting error like

    System.NullPointerException: Attempt to de-reference a null object
    Class.testemail.: line 10, column 1



    page code:









    class


    public class testemail
    {
    private final List contactids;
    public List con;
    public testemail(ApexPages.StandardController controller)
    {
    con = [SELECT Id FROM Contact limit 25 ];
    for(Integer i=1;i<25;i++)
    {
    contactids.add(con[i].Id); //line 10, column1
    }
    }

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


    }

    ReplyDelete
  23. @Anonymous:
    We need to instantiate contactids variable

    ReplyDelete
  24. System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, Visualforce templates are not currently supported for mass email.: []

    ReplyDelete
  25. hi, if want to send a mass email a custom object??

    ReplyDelete
  26. thanks a lot.........This is what i m looking for!

    ReplyDelete
  27. how to add the attachment to the mail... plz help me

    thanks
    srini

    ReplyDelete
  28. I copy & paste the code but i am getting an error please solve me.

    Error:-

    System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target address (target, to, cc, bcc): []
    Error is in expression '{!SendEmail}' in component in page sampath:testemail

    Class.sampath.testemail.SendEmail: line 13, column 1

    Thanks
    sam

    ReplyDelete
  29. hi,
    can anyone pls share the code for sending a mail daily to the customer if the status is paid .pls

    ReplyDelete
  30. SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target address (target, to, cc, bcc): []
    Error is in expression '{!SendEmail}' in component in page testemail

    ReplyDelete
  31. This comment has been removed by a blog administrator.

    ReplyDelete
  32. This comment has been removed by a blog administrator.

    ReplyDelete
  33. When I used SetTargetObjectId for MassEmailMessage

    it keeps showing me the error Method does not exist or incorrect signature

    I thought I may give the wrong value, and I tried Set, List etc.

    None of them works, something I missed?

    ReplyDelete
  34. y u use odd code ?

    ReplyDelete
  35. Hi All,

    Is there any possibility to design a Mass Email blast for Custom objects.
    If , Yes please send me the code in my email Phaneendra.arigachetta@gmail.com

    Thanks,
    PHaneendra

    ReplyDelete
  36. Hi ... I am facing a problem while sending email to contacts.
    My requirement is like: When a contact record is updated, I have to send a email to all the contact records of updated contact account. I am sending email using singleEmailMessage method because the TargetObjectId should be of updated contact so that merge fields show correctly. Now when I update contact record all contact's receive single email except the contact which updated, updated contact receive multiple emails. I debug the issue and found that it happens because updated contact id is set in targetObjectId. Could you please suggest me how can I fix this issue so that updated contact also receive single email.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Get all the Account related contacts into a list as below
      Messaging.Singleemailmessage email = new Messaging.Singleemailmessage();
      String [] toaddress= new list();
      for(Contact c:[select id,email from contact where Accountid =: id])
      email.setToAddresses(toaddress);
      toaddress.add(string.valueOf(c.email));

      Delete
  37. hi i am getting error like System.NoAccessException: The organization is not permitted to send email
    how can i resolve this issue

    ReplyDelete
  38. This comment has been removed by a blog administrator.

    ReplyDelete

AD