Friday, November 28, 2014

Creating an Inbound Email Service in Salesforce.

Creating an Inbound 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.

An email services only process its messages it receive one of it’s address

For example you can create email service that automatically create its contact record based on contact information in your email messages.


The general template to create the apex class for the email services is:


Create Email Handler class Shell:-

A class must implements the Messaging.InboundEmailHandler interface and this interface has single method that call handleInboundEmail messages.

The IDE provides a template for creating an inbound email service handler calss.


1. Create the Apex email handler class.
   A. In the IDE, right-click the project folder and select New | Apex Class.
   B. Enter the Name ProcessContactApplicantEmail and click Finish.


Apex Class:

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

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        Contact contact = new Contact();
        contact.FirstName = email.fromname.substring(0,email.fromname.indexOf(' '));
        contact.LastName = email.fromname.substring(email.fromname.indexOf(' '));
        contact.Email = envelope.fromAddress;
        insert contact;
        System.debug('====> Created contact==> '+contact.Id);
        if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
          for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
            Attachment attachment = new Attachment();
            // attach to the newly created contact record
            attachment.ParentId = contact.Id;
            attachment.Name = email.binaryAttachments[i].filename;
            attachment.Body = email.binaryAttachments[i].body;
            insert attachment;

        return result;

2. Create the inbound email service.
    A. In the UI, navigate to Setup | Build | Develop | Email Services.
    B. Click New Email Service.
    C. Enter the following information:
        i. Email Service Name: CandidateSubmission
        ii. Apex Class: CandidateEmailHandler
        iii. Accept Attachments: All
        iv. Advanced Email Security Settings: (cleared)
        v. Accept Email From: Enter your email address or leave blank
        vi. Active: (selected)
        vii. Set all Failure Response Settings to: Bounce Message
    D. Click Save and New Email Address.
    E. Enter the following information:
        i. Email Address: CandidateSubmission
        ii. Active: (selected)
        iii. Context User: (your name)
        iv. Accept Email From: (enter your email address or leave blank)
    F. Click Save and notice the resulting Email Address.

One of the difficult thing about email service is debugging them. You can either create a test class for this or simply send the email and check the debug logs. Any debug statements you add to your class will show in the debug logs. Go to Setup -> Administration Setup -> Monitoring -> Debug Logs and add the Context User for the email service to the debug logs. Simply send an email to the address and check the debug log for that user.

The following unit test class will get you 100% code coverage.

 * @Description: Test class for  ProcessContactApplicantEmail
private class ProcessContactApplicantEmail_Test {

    static testMethod void myUnitTest() {
       // create a new email and envelope object
      Messaging.InboundEmail email = new Messaging.InboundEmail() ;
      Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
      // setup the data for the email
      email.subject = 'Test Contact Applicant';
      email.fromname = 'FirstName LastName';
      env.fromAddress = '';
      // add an attachment
      Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
      attachment.body = blob.valueOf('my attachment text');
      attachment.fileName = 'textfile.txt';
      attachment.mimeTypeSubType = 'text/plain';
      email.binaryAttachments =
        new Messaging.inboundEmail.BinaryAttachment[] { attachment };
      // call the email service class and test it with the data in the testMethod
      ProcessContactApplicantEmail emailProcess = new ProcessContactApplicantEmail();
      emailProcess.handleInboundEmail(email, env);
      // query for the contact the email service created
      Contact contact = [select id, firstName, lastName, email from contact
        where firstName = 'FirstName' and lastName = 'LastName'];
      // find the attachment
      Attachment a = [select name from attachment where parentId =];


Email Logs:

  • Are csv files that can be accessed by clicking Setup -> Monitoring -> Email Log Files. The logs contain the emails sent/received through salesforce along with the email addresses, date/time, delivery status and error codes. But, it does NOT capture the body or attachments of an email.
  • Since developers do not have access to system log files in the context of an inbound email class, they may want to create a custom object to log any exceptions or debug statements.


Post a Comment

| ,