,

Handling Inbound Emails

Email has become one of the most common communication methods in the electronic world. The Force Platform has done a lot of the heavy lifting for receiving inbound email, in terms of security, authenticity, and parsing of messages.

In order to handle incoming emails, you need to perform two tasks. The first is to create an Apex class that implements a specific Apex interface for the incoming emails. The second is to perform some setup tasks to enable this interface through the Email Services page.

Once you have completed these tasks, the Force Platform automatically generates an email address that receives incoming messages. The receipt of a message triggers the execution of this functionality, implemented in the same Apex class.

Implementing the InboundEmailHandler Interface

The role of interfaces in Apex is to describe a set of methods in terms of their names, parameters and the type of data they return. These three aspects are known as a methods signature. An interface does not define the actual code within the methods, just the signature for the methods.

In this section you will implement methods for a Force Platform-supplied interface, enabling the platform to call your code when an inbound email message arrives.

The first step to handling inbound emails is to create an Apex class. The class, which was loaded into your organization with the initialization procedure called out at the beginning of the chapter, uses the implements Apex language keyword to create a class that implements the Force Platform Messaging.InboundMailHandler interface. This class includes a method that matches the signature defined in the interface.

The following code sample shows a basic implementation of this interface:

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

The class and the interface methods use the global access modifier, covered in Chapter 10: Apex. The handleInboundEmail method uses two parameters that are passed to your code by the Force Platform. These parameters contain information taken from the inbound message, relieving you of the need to parse the raw SMTP message.

The code samples in this section are taken from the full implementation of the ProcessApplicants Apex class, which handles the incoming emails. This class was loaded into your organization as part of the setup process for this chapter, described above. You can view the code in this class in full from either your Eclipse environment or through Setup Develop Apex Classes.

The email parameter represents the email itself, and gives you access to various header information, such as from, to, and cc, as well as the body of the email and potentially any attachments, covered later in this chapter. The envelope parameter provides additional information relating specifically to the actual email addresses used for sending and receiving the email. The InboundEmailResult object and result is used to return any errors handling the message to the calling Apex class.

Access to additional email information

The headers field on the InboundEmail class also provides access to information not explicitly exposed as fields, such as RFC 2822 headers like Message-ID, Date, and also any custom headers as defined by the sending server.

Only text-based attachments with a MIME type of either text or application/octet-stream are supported, in the later case only file names ending with .vcf or .vcs extension specifically. Binary attachments are available through the bindaryAttachments field and text through the textAttachments field on the InboundEmail class. Attachments within the email, such as inline graphics, are not supported.


You have a variety of options to specify how your Apex message handler handles the information in the incoming email message. The example in this chapter makes some basic assumptions about the email content in terms of the subject and body contents. The subject of the email is always the Name of the record for the position in the Position__c object, which was defined as an auto-number field that produces values like POS-00004. Any attachments on an incoming email is automatically attached to the resulting Job Application record.

The figure below shows an example of the type of email the code in this chapter is expecting.

Figure 199. Sample incoming email


These emails are generated from hyperlinks on a Visualforce page in the Universal Containers recruiting application.

Note

In Chapter 14: Taking Your Application Public with Force Platform Sites, you will learn how to use Force Platform Sites to expose a Visualforce page to the outside world.


The links automatically add the Position name as the subject and direct the email to the correct Force Platform email address.

Your application will use a Visualforce page to create incoming email applications. This Visualforce page, availablePositions, and the custom controller it uses, the AvailablePositionsController, were also loaded into your organization with the initialization scripts described at the start of this chapter.

Parsing the Inbound Message

The following code fragment from the processApplicant class shows how the Position name in the subject line, and the candidates’ first and second names are read from the email parameter via the fromName and subject fields.

String firstName =
  email.fromName.substring(0,email.fromName.indexOf(' '));
String lastName =
  email.fromName.substring(email.fromName.indexOf(' '));
String positionName = email.subject;

The code shown in the next fragment is used to obtain the phone number, parsed from the plainTextBody field.

integer phoneMatchIdx = email.indexOf( PHONE_MATCH );
if(phoneMatchIdx==-1)
  throw new ProcessApplicantException(
     'Please state your phone number following
        Phone: in your message.'),
String phoneNumber =
  email.plainTextBody.substring( phoneMatchIdx +
    PHONE_MATCH.length() );

The text string Phone: is placed in a static String variable PHONE_MATCH at the top of the ProcessApplicants class for reuse purposes. The indexOf method searches the plainTextBody field for the first occurrence of ‘Phone:’, with the assumption that the next characters are the phone number. The search either returns an index for the initial position of the text for the phone number or -1 if no match is found. If no match is found, the indexOf function returns -1, which causes an exception to be thrown and feedback is sent the user.

Catching errors

In the code sample below, you can see that the class throws its own exception in the event of a logical error. The message field on the Messaging.InboundEmailResult class is then used to catch potential problems in the incoming emails, such as missing required information. The code sample used in this chapter uses an Apex exception class and a try/catch block to manage error handling in the handler as shown below.

Messaging.InboundEmailResult result = new
Messaging.InboundEmailresult();
  try
  {
    // Obtain the applicants Phone number from the message body
    integer phoneMatchIdx =
      email.plainTextBody.indexOf( PHONE_MATCH );
    if(phoneMatchIdx==-1)
      throw new ProcessApplicantException(
         'Please state your phone number following Phone:
          in your message.'),
    String phoneNumber =
      email.plainTextBody.substring( phoneMatchIdx +
        PHONE_MATCH.length() );
    // ...
    result.success = true;
  }
  catch (Exception e)
  {
    // Return an email message to the user
    result.success = false;
    result.message =
       'An error occurred processing your message.' +
         e.getMessage();
  }
  return result;


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.165.171