Difference between revisions of "HowTo:Handle Incoming Emails Programmatically"

From LongJump Support Wiki
imported>Aeric
imported>Aeric
 
(18 intermediate revisions by the same user not shown)
Line 1: Line 1:
The sample class below logs an incoming email message in an EmailLog object (an object that needs to be created for the purpose). In addition to processing the messages, it handles any incoming attachments. It uses each attachment's content type (MIME type) to determine if the attached file contains an image.
<noinclude>
{{Orientation|Developers|Advanced|20}}
</noinclude>===Overview===
You can use Java classes to define your own email handler, and use the platform [[API]]s to carry out platform operations.
 
;The Process:
# Create the Sample Handler class defined below.
# As an admin, in [[External Email Tracking]], configure the class as the email handler for your tenancy. (See [[External_Email_Tracking#Administration_Setup|Administration Setup]])
# As a user, under [[My Email-to-|My Email-to-{domain}]], get the email address to send to, and specify the address(es) you'll be sending from.
# 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 <tt>processEmail</tt> method defined by the <tt>EmailHandler</tt> interface. That method takes an <tt>Email</tt> object. (The platform uses the incoming email to create that object, and sends it to your handler.)


''Learn more:''
''Learn more:''
Line 5: Line 19:
:* [[MIME type]]s
:* [[MIME type]]s


:<syntaxhighlight lang="java" enclose="div">
<syntaxhighlight lang="java" enclose="div">
package com.platform.demo.mail;
package com.platform.demo.mail;


Line 18: Line 32:
  * Prerequisite: An EmailLog Object in the platform with the following fields:
  * Prerequisite: An EmailLog Object in the platform with the following fields:
  * <pre>
  * <pre>
  *    Field      Type     Description
  *    Field      Type         Description
  *    --------  ------   ---------------------
  *    --------  ------       ---------------------
  *    to_list    String  List of addresses
  *    to_list    TextArea    List of addresses
  *    from_addr  String  Sender's email address
  *    from_addr  TextField    Sender's email address
  *    subject    String  Message heading
  *    subject    TextField    Message heading
  *    body      String  Message content
  *    body      RichTextArea Message content
  *    file_1    File     As many fields as needed for the maximum
  *    file_1    File         As many fields as needed for the maximum
  *    ...                   number of attachments you expect to process.
  *    ...                   number of attachments you expect to process.
  *    file_N  
  *    file_N  
  *    image_1    Image   Ditto.
  *    image_1    Image       Ditto.
  *    image_N  
  *    image_N  
  * </pre>
  * </pre>
  *    Note:
  *    Note:
  *    Fields of type Image could also be used for attachments. The difference
  *    Fields of type Image can also be used for attachments.  
  *    in the object is that an image (or its thumbnail) is displayed when the
  *    The difference is that an Image (or its thumbnail) is displayed  
  *    record is displayed, whereas a file isn't.  
  *    when a record is viewed. A File isn't.  
  */
  */
public class SampleEmailHandler implements com.platform.api.mail.EmailHandler
public class SampleEmailHandler implements com.platform.api.mail.EmailHandler
Line 42: Line 56:
       {
       {
         // Log the incoming message
         // Log the incoming message
         Functions.debug ("In: " + email.toString() );
         Functions.debug ("Email: " + email.getSubject() );


         // Store email data as parameters for the record we'll create.
         // Store email data as parameters for the record we'll create.
Line 65: Line 79:
             String filename = attachments[i].getFileName();
             String filename = attachments[i].getFileName();


             // Deterine the field name to use for the attachment.
             // Determine the field name to use for the attachment.
             // Here, we assume that for a MIME type like "image/jpg",
             // Here, we assume that for a MIME type like "image/jpg",
             //    the value is stored in an Image field.  
             //    the value is stored in an Image field.  
Line 81: Line 95:
             // Decode each attachment & save it as a record parameter.
             // Decode each attachment & save it as a record parameter.
             byte[] body = codec.decode(attachments[i].getBody());
             byte[] body = codec.decode(attachments[i].getBody());
             PlatformFileBean filebean = new PlatformFileBean("", filename, new String(body));
             PlatformFileBean filebean =
              new PlatformFileBean("", filename, new String(body));
             params.add(fieldname, filebean);
             params.add(fieldname, filebean);
         }
         }
Line 93: Line 108:
         {
         {
             String record_id = result.getID();
             String record_id = result.getID();
             Functions.debug("Record Id: " + record_id);
             Functions.debug("EmailLog Record Added: " + record_id);
         }
         }
         else
         else
         {
         {
             Functions.debug("Message: " + result.getMessage());
             Functions.debug("EmailLog Failure: " + result.getMessage());
         }
         }
       }
       }
       catch (Exception e)
       catch (Exception e)
       {
       {
         Functions.debug("Exception:" + e.getMessage());
         Functions.debug("EmailLog Exception:" + e.getMessage());
       }
       }
   }
   }
}
}
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 17:48, 22 June 2012

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());
      }
   }
}