+ Start a Discussion
Ellsa JamesEllsa James 

How do I create an email service and class to associate inbound email with an existing record?

We are using a custom object (instead of Case object) to handle our requests. I am looking to add the functionality to attach incoming emails to their associated request record similar to the functionality offered by email to case. We will only be attaching to existing records and Not creating new ones.

I believe this can be accomplished via an email service and handler class. I am ok with creating the email service but I need some pointers or code example of what the handler class would look like?

Thank you.
Sai Ram ASai Ram A
global class InboundEmailServiceExamplecreateContact implements Messaging.InboundEmailHandler {
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
          // Create an InboundEmailResult object for returning the result of the 
          // Apex Email Service
          Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
          String myPlainText= '';
        // Add the email plain text into the local variable 
        myPlainText = email.plainTextBody; //
        System.debug('*****Email Body : ' + myPlainText ); 
        // New Task object to be created
      Contact[] newContact = new Contact[0];
        try {
      Contact vCon = [SELECT Id, Name, Email FROM Contact WHERE Email = :email.fromAddress LIMIT 1];
        newContact.add(new Contact(Description =  myPlainText,
           LastName = email.fromAddress,
           LeadSource = 'Web',
           Status__c = email.subject,
           Birthdate = System.Today()+1));
     // Insert the new Task 
     insert newContact;
      System.debug('*****New Contact Object: ' + newContact );   
    // If an exception occurs when the query accesses 
    // the contact record, a QueryException is called.
    // The exception is written to the Apex debug log.
   catch (QueryException e) {
       System.debug('Query Issue: ' + e);
   // Set the result to true. No need to send an email back to the user 
   // with an error message
   result.success = false;
   // Return the result for the Apex Email Service    
          return result;
Sample Code!!

Tad Aalgaard 3Tad Aalgaard 3
This does not address the original request of associating the email message with an existing record.