Email Services in Salesforce with simple example

What is an Email service in Salesforce?

Email services are automated processes that use Apex classes to process the contents, headers, and attachments of inbound email.

You can associate each email service with one or more Salesforce-generated email addresses to which users can send messages for processing.
The general template to create the apex class for the email services is:

How Email Services works in Salesforce
How Email Services works in Salesforce

global class myHandler implements Messaging.InboundEmailHandler {
	  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
		  Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
          return result;

Example of Email Service – Creating Contact from email
Presumption –

  • Subject should contain word “Create Contact”
  • Body contains only Contact Name.

Apex Code with test method:

 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
global class CreateContactFrmEmail implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

		String subToCompare = 'Create Contact';

			Contact c = new Contact();
			c.LastName = email.plainTextBody;
			insert c;

                // Save attachments, if any
        	for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
          	Attachment attachment = new Attachment();

          	attachment.Name = tAttachment.fileName;
          	attachment.Body = Blob.valueOf(tAttachment.body);
          	attachment.ParentId = c.Id;
          	insert attachment;

        	//Save any Binary Attachment
        	for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
          	Attachment attachment = new Attachment();

          	attachment.Name = bAttachment.fileName;
          	attachment.Body = bAttachment.body;
          	attachment.ParentId = c.Id;
          	insert attachment;

	result.success = true;
        return result;

    static testMethod void testCreateContactFrmEmail() {
    	Messaging.InboundEmail email = new Messaging.InboundEmail() ;
        Messaging.InboundEnvelope env    = new Messaging.InboundEnvelope();

        email.subject = 'Create Contact';
        email.plainTextBody = 'FromEmail';
        env.fromAddress = '';

        CreateContactFrmEmail creatC = new CreateContactFrmEmail();
        creatC.handleInboundEmail(email, env );

After creating the above Apex class, click Your Name | Setup | Develop | Email Services.

  • Click New Email Service to define a new email service.
  • Select above apex class, add email address from where to accept the request and activate the service.
Email Service Information - Salesforce
Email Service Information – Salesforce

After filling the form, click on “Save and New Email Address”

Email Address Information - Salesforce
Email Address Information – Salesforce

Note: The domain name in Email address must qualify the domain name entered at “email services” in first step. For example : we have entered “” in first step that means it will accept the email address only from the and that’s why in second step I have used email address displayed in screen shot.
After all the above steps, one email address is generated by the salesforce. Send the email to that address with subject line “Create Contact” and contact name in email body.
In the above tutorial, I have used very simple example just to demonstrate that how the email services works in the salesforce.

Governance limit of Email services in salesforce:
Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case, can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day, depending on how you configure the failure response settings for each email service. Salesforce calculates the limit by multiplying the number of user licenses by 1,000, up to a daily maximum of 1,000,000



, , ,


Related Posts


50 responses to “Email Services in Salesforce with simple example”

  1. Sukumarmalladi22 Avatar

     public class sendemail {

    public String subject { get; set; }
    public string body{get;set;}
    string ls;
    public string getinfo()
    return ls;

    public PageReference send() {

    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    String[] toAddresses = new string[]{‘’};
     email.setSubject( subject );
     email.setToAddresses( toAddresses );
     email.setPlainTextBody( body );
            Messaging.SendEmailResult [] r =  Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
            return null;

    Unknown property ‘String.subject’ my error plz tell me

    iam trying to send the email (………

    1. JitendraZaa Avatar

      Can you please try this - 
       email.setSubject(‘Test Email’);
      instead of
       email.setSubject( subject );

      1. Kumar Avatar

        Hello Jithendra,

        I have a scenario like want to accept emails only and if any other email comes which should have or or any other domain name with #Support#. How can I achieve this, where can I validate this means in apex end or configuration ‘Accept Email Form’ section?

        Please suggest.

        Thanks in Advance


        1. JitendraZaa Avatar

          Hello Kumar,
          It cannot be done in “Config” section because your requirement is very advance. So better to use inside Email Service Apex class only.

          1. yeswanth Avatar

            Hello Jithendra,

            i have a scenario like using email service if i send a pdf in the outlook mail it have to create new record in Ticket object. in pdf i have some data so it has to parse data and create record in object.In pdf i have some data which it matches to object fields

            Thanks inAdvance

  2. Ramu Feb14 Avatar
    Ramu Feb14

    Hi all, I’m trying to install the IDE plugin. I found it, it started downloading, but once the plugin goes to install I get the following error at about 45% completion:

    “Installing software has encountered a problem. An error occurred while collecting items to be installed” 

    When I click details about this error, I get the following. Anyone know how to fix this and get the plugin installed? Thanks in advance

    Code: [Select all] [Show/ hide]An error occurred while collecting items to be installed
    session context was:(profile=SDKProfile, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
    Problems downloading artifact: osgi.bundle,com.salesforce.ide.api,
    MD5 hash is not as expected. Expected: 97a6329f82c422a61e9b1bc28be7cace and found ef8b1c2b63c7d04acaa6bf41f4b8570c.

  3. Anand Avatar

    how to use it after doing like this

    1. Jitendra Zaa Avatar
      Jitendra Zaa

      Send Email to that Email Service. Contact will be created in Salesforce.

  4. Mahesh Avatar

    thanks for the info.

  5. pankaj Avatar

    very helpful..thanks a lot

  6. […] How to Test Email Services ? […]

  7. Ram Avatar

    hi i have created a custom email service. should i send the email to the very long sf generated email address or can i send it to a smaller one like which in turn will forward to this email address.

    1. JitendraZaa Avatar

      Email to anyone of them will work. At the end, it is important that long email should get email.

      1. Ram Avatar

        cool. Any idea how bounced email messages work and whether they are stored in the email message object? I need to update certain fields when a email bounces(when being sent from Salesforce)

        1. JitendraZaa Avatar

          Hi Ram, We dont have that information exposed in API yet…

      2. Mazhari Avatar

        hello sir i wrote apex class and created email services but it is only working when i send the email to the very long sf generated email address and lead is generating but i need to generate lead when i give small address like

        1. Sufyan Avatar

          Hi bro have you got the answer that how to send email to short id but like you have mentioned

        2. sufyan Avatar

          bro have you got the answer i’m also having the same issue

  8. Pavan Avatar

    My assignment rule is not firing on case created through Email services. Can you please guide what could be the issue

    1. JitendraZaa Avatar

      Hi pavan, check assignment rule criteria and support settings under case.

  9. Arvind Yadav Avatar
    Arvind Yadav

    if we have two support email Ids where we are getting emails from our customers . how can we identify on which support email they have send there case .??

    thanks in advance !

    1. JitendraZaa Avatar

      In that case, create two email services and write custom logic in each email service. You can do anything to identify as they are having different classes.

      1. Arvind Yadav Avatar
        Arvind Yadav

        thanks for the reply .

  10. jay kumar Avatar
    jay kumar

    Hi Jitendra,

    I have following requirment,

    For email2cases, currently salesforce creates cases without consider if constomer wants p1 or p2 severity logged, it simply takes email and logs cases.
    can we have customers use template and salesforce considers whats in template and logs case so that case fields are populated as per what customer seleected like P1 for severity.

    I believe email service as you mentioned is our only option?
    If so, how do i parse email body for lets say if we have 4 fields like this in email body which customer has sent to us assuming anuthing in the brackets is field name[ ]




    1. JitendraZaa Avatar

      Hello Jay, We cant use Email-to-Case to decide severity.

      For Email Services, in your case, You will need to write Parser logic to fetch your field values and decide on severity.

  11. Dileep Avatar

    Hi Jitendra,

    I have an issue on this can i send all the scenerio if could help me.

  12. raviteja Avatar

    Hi jitendra,
    I am getting the following error while implementing the above code.

    (Undelivered): 554 The apex class CreateContactFrmEmail failed due to: System.NullPointerException: Attempt to de-reference a null object

  13. Dinesh Singla Avatar
    Dinesh Singla

    Hi Jitendra,

    You are using a insert operation in for it okay to use insert in for loop in email services

    1. Jitendra Zaa Avatar

      That’s very good question 🙂 . I didn’t found any documentation saying Email services execute in Bulk. Whenever email is sent to email address, this class will be executed and for every email this class will have its own transaction. So, I guess its ok to write DML in loop. If you see this example then here also, DML is written in loop –

      1. Dinesh Singla Avatar
        Dinesh Singla

        I already saw that but did not found any any thing.
        that’s why i posted here 😉
        Thanks for your clarification.

  14. harshad kokate Avatar
    harshad kokate

    Hi how to disable the auto replay ?

  15. SFCLR Avatar

    I am exactly replicating the steps, however its not working for me. No new contact is generated after doing so..can you guess the issue?

    1. Jitendra Zaa Avatar

      Is your email service apex class is being invoked at all, did you checked debug logs ?

      1. H John Avatar
        H John

        Hi it is giving me this error “Attempt to de reference a null object on line
        for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments)

  16. Sakthivakeswaran Avatar

    Hai Mr.Jitendra, Kindly reply when Possible for the question posted below……

    1: I could not able to find what is exact limit of single email and mass email when sending email From apex code using single and mass email methods in salesforce,

    2: And another issue with me is i could not able to find difference between single and mass emails. Kindly help me to figure out limits and difference.

  17. Nilesh Borse Avatar
    Nilesh Borse

    Nice Tutorial…
    Instead of putting salesforce email service email ID in To, i putted it in BCC, and i can see the inbound handler is being executed.

  18. Richa Avatar

    Hi Jitendra,

    I have a requirement wherein client wants a checkbox sort of indicator which decides whether case is to be created for that mailbox or not. In case, the checkbox is selected to ‘No’, then the inbound email should be stored as a record in a custom object. Is something of that possible?

    Thanks in advance.

  19. Raj Avatar

    Hi Jitendra,

    Can we write test method in the same class. I am getting following error:
    Error: Compile Error: Defining type for testMethod methods must be declared as IsTest at line 41 column 28

    1. Jitendra Avatar

      Hi Raj,
      Its not possible in latest Salesforce API’s. Previously it was possible.

    2. Prab Avatar

      Hi Raj.

      What’s the solution for this? i can see the same error if i use this code.
      Do i have to add @isTest class with this code?

  20. Larry Trudelle Avatar
    Larry Trudelle

    Hi. Hopefully you can help me.

    I have set “Email to Salesforce” to use Gmail account. SF assigned an email address
    “ In Gmail I have setup Forward to that email.

    If I send an email to a client such as, the email is sent.
    Wwhen that client replies, the email goes through Gmail and is forwarded to SF.

    BUT… SF rejects the email with a message … (Undelivered): 551 SenderAuthorization: is not authorized to send emails to this service.

    AFter hours of searching, it seems many people have the same problem with SF.

    Do you know how to solve this.

    Larry Trudelle
    Toronto, Canada

    1. Rupesh Patil Avatar
      Rupesh Patil

      I was also faced the same issue. I overcame it by unchecking the ‘Advanced Email Security Settings’ checkbox in Email Service.

  21. Nilesh Tanwar Avatar
    Nilesh Tanwar

    Hi Jitendra,

    I am stuck with a requirement.

    I am required to send an email from case via Email Related List. If I am sending an email to Invalid Contact. The bounced email received must be attached to case.

    I have tried below stuff:
    1. Configured email to case.
    2. Created an email to service with a Auto generated long email address.
    3. Enabled email forwarding from step 1 email id to step 2 email id.
    4. Enabled bounce management in my Organization and also enabled send back bounce notification to sender.

    But I am not receiving the bounced emails back.

    Where as if I send an email from step 1 mail id directly (after logging into mailbox 1 )to the invalid contact, I am receiving back the bounced emails.

    Please help if you have any idea or worked on similar requirement.

  22. John Sadler Avatar

    Howdy. Any thoughts on why an Email Service would receive emails from 2 domains and not my own business domain?
    I have cleared both boxes of domains and still get emails from or but not It was working but now will not.

  23. ketansing pawar Avatar
    ketansing pawar

    Hi Jitendra,

    Can we schedule this email service.


  24. Shawn Amar Avatar
    Shawn Amar

    Hi Jitendra,
    Thanks for posting this. I had the following error:
    The apex class CreateContactFrmEmail failed due to: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ExampleTrigger: execution of AfterInsert

    caused by: line 5, column 9: Variable does not exist: EmailManager: []
    I am not calling the EmailManager in my code.


  25. Anant Pareek Avatar
    Anant Pareek

    Hi Jitendra
    I have a CSV containing 1000 records and i want to take that data and store it inside he object in my org that is once i sent my csv via mail than automatically all records on that object are created in salesforce.
    Can you help me??
    Anant Pareek

  26. Vibin Avatar

    Hello Jitendra,

    How we could migrate email services with package.xml file

  27. Vinayak Avatar

    Good ! But i have one question….we have to send email to only salesforce generated email, then this class execute…but what if , If lead send email from their email id and I want to execute that inbound class for email we receiving from leads…?? leads dont know that salesforce generated email id…so how to execute that inbound class for incoming emails from existing lead or new leads…Please Reply sir

  28. Max Avatar

    Thanks for this article . However I have a question if I have 2 different email addresses that use the email service class but based on which addresses are email I need to do different logic . Could I do a switch statement on the to address field in order to branch my logic based on which email address the inbound email come from ?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading