HowTo:Handle Incoming Emails Programmatically

HowTo:Handle Incoming Emails Programmatically

From LongJump Support Wiki

HowTo:Handle Incoming Emails Programmatically
Jump to: navigation, search

For:   Developers
Level: Advanced
Time: 20 minutes

See more:
    ◾ HowTo Guides

Overview

You can use Java classes to define your own email handler, and use the platform APIs to carry out platform operations.

The Process
  1. Create the Sample Handler class defined below.
  2. As an admin, in External Email Tracking, configure the class as the email handler for your tenancy. (See Administration Setup)
  3. As a user, under My Email-to-{domain}, get the email address to send to, and specify the address(es) you'll be sending from.
  4. Try it out by sending a message to the platform.

Sample Handler

This sample class logs an incoming email message in an EmailLog object (an object that needs to be created for the purpose). In addition to logging the messages, it stores any incoming attachments. It uses each attachment's content type (MIME type) to determine if the attached file contains an image.

It works by implementing the processEmail method defined by the EmailHandler interface. That method takes an Email object. (The platform uses the incoming email to create that object, and sends it to your handler.)

Learn more:

package com.platform.demo.mail;

import com.platform.api.mail.*;
import com.platform.api.*;
import com.platform.beans.*;
import com.platform.api.utility.Base64Codec;   // For decoding attachments

/**
 * Handle an incoming email message by creating a record.
 *
 * Prerequisite: An EmailLog Object in the platform with the following fields:
 * <pre>
 *    Field      Type         Description
 *    --------   ------       ---------------------
 *    to_list    TextArea     List of addresses
 *    from_addr  TextField    Sender's email address
 *    subject    TextField    Message heading
 *    body       RichTextArea Message content
 *    file_1     File         As many fields as needed for the maximum
 *     ...                    number of attachments you expect to process.
 *    file_N
 *    image_1    Image        Ditto.
 *    image_N
 * </pre>
 *    Note:
 *    Fields of type Image can also be used for attachments.
 *    The difference is that an Image (or its thumbnail) is displayed
 *    when a record is viewed. A File isn't.
 */

public class SampleEmailHandler implements com.platform.api.mail.EmailHandler
{
   public void processEmail(Email email)
   {
      try
      {
         // Log the incoming message
         Functions.debug ("Email: " + email.getSubject() );

         // Store email data as parameters for the record we'll create.
         // (All components of an email are available.)
         Parameters params = Functions.getParametersInstance();
         params.add("to_list", email.getToAddresses());
         params.add("from_addr", email.getFromAddress());
         params.add("subject", email.getSubject());
         params.add("body", email.getPlainTextBody());
         com.platform.api.mail.Attachment[] attachments =
            email.getAttachments();

         int file_num = 1;
         int image_num = 1;
         Base64Codec codec = new Base64Codec();
         for (int i = 0 ; i < attachments.length; i++)
         {
            // Process attachments
            // Note: Attachments without corresponding fields are ignored.
            // Throw an exception (or least log an message) if the number
            // of attachments exceeds the number of fields defined for them.                
            String filename = attachments[i].getFileName();

            // Determine the field name to use for the attachment.
            // Here, we assume that for a MIME type like "image/jpg",
            //    the value is stored in an Image field.
            String mimetype = attachments[i].getContentType();
            String fieldname = "";
            if (mimetype.startsWith("image/"))
            {
               fieldname = "image_" + (image_num++);
            }
            else
            {
               fieldname = "file_" + (file_num++);
            }

            // Decode each attachment & save it as a record parameter.
            byte[] body = codec.decode(attachments[i].getBody());
            PlatformFileBean filebean =
               new PlatformFileBean("", filename, new String(body));
            params.add(fieldname, filebean);
         }

         // Create a new record from the email.
         // (Do any processing you like, here.)
         Result result = Functions.addRecord("EmailLog", params);

         // Verify the add succeeded. Log any errors.
         if (result.getCode() == 0)
         {
            String record_id = result.getID();
            Functions.debug("EmailLog Record Added: " + record_id);
         }
         else
         {
            Functions.debug("EmailLog Failure: " + result.getMessage());
         }
      }
      catch (Exception e)
      {
         Functions.debug("EmailLog Exception:" + e.getMessage());
      }
   }
}
Personal tools