Tuesday, 15 November 2016

Apex Email Service | InboundEmail Object | Messaging.InboundEmailHandler in salesforce


Email Service

Email service is special processes that use Apex classes to process incoming email messages. When you set up an email service, we need to generate a special email address in which salesforce will receive your emails. For same we need to create one apex class to implement Messaging.InboundEmailHandler interface . The email services will then invoke a handleInboundEmail method on the Apex class whenever an email is received on the email address.


NOTE:- Before creating email services we need to create Apex classes that implement the Messaging.InboundEmailHandler interface.


STEP 1:- Create one Apex class with Messaging.InboundEmailHandler

global class EmailServiceExample implements Messaging.InboundEmailHandler 
{
 global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,Messaging.InboundEnvelope env)
 {
  // Create an InboundEmailResult object for returning the result of the Apex Email Service
  Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
  try 
  {
   List<Contact> contList= [SELECT Id, Name, Email FROM Contact WHERE Email = :email.fromAddress LIMIT 1];
   Task taskObj = new Task();
   taskObj.Description =  email.plainTextBody;
   taskObj.Priority = 'Normal';
   taskObj.Status = 'Inbound Email';
   taskObj.Subject = email.subject;
   taskObj.IsReminderSet = true;
   taskObj.ReminderDateTime = System.now()+1;
   if(contList.size()>0)
   {
    taskObj.WhoId =  contList[0].Id;
   }    
   insert taskObj;    
  }
  catch (Exception e) 
  {
     System.debug('Exception : ' + e);
  }
  result.success = true;
  return result;
 }
}


STEP 2 :- Setup Email service

1) Go to Setup -->Develop->Email Services



2) Click on New Email Service
3) Then complete all below information



4) then click on SAVE button.

STEP 3 :- Generate an email address

1) Click on "New Email Address" button

2) Then add all below detail

 3) Then click on SAVE button.

 You will see a new email address that salesforce will monitor, emails received on this address will trigger the associated Apex code.



STEP 4 :- Testing of email service

1) Create one contact with sender email address.
2) Then send email from given email domain to same email address.



Please check next post for Apex Email Service Test class

Thanks,
Amit Chaudhary