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';

		if(email.subject.equalsIgnoreCase(subToCompare))
		{
			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 = 'ilovenagpur@gmail.com';

        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 “gmail.com” in first step that means it will accept the email address only from the gmail.com 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

  • Sukumarmalladi22

     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[]{‘username@gmail.com’};
     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 (………@gmail.com)

    • JitendraZaa

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

      • Kumar

        Hello Jithendra,

        I have a scenario like want to accept tcs.com emails only and if any other email comes which should have #Support#@gmail.com or #Support#@yahoo.com 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

        Kumar

        • JitendraZaa

          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.

  • Ramu Feb14

    Hi all, I’m trying to install the Force.com 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,23.0.2.201201091635.
    MD5 hash is not as expected. Expected: 97a6329f82c422a61e9b1bc28be7cace and found ef8b1c2b63c7d04acaa6bf41f4b8570c.

  • Anand

    how to use it after doing like this
     

    • Jitendra Zaa

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

  • Mahesh

    thanks for the info.

  • pankaj

    very helpful..thanks a lot

  • Pingback: How to pass Salesforce Dev 501 Certification | Shiva Blog

  • Ram

    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 abcd@gmail.com which in turn will forward to this email address.

    • JitendraZaa

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

      • Ram

        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)

        • JitendraZaa

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

  • Pavan

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

    • JitendraZaa

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

  • 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 !

    • JitendraZaa

      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.

      • Arvind Yadav

        thanks for the reply .