Create Record via Inbound Email (Email Services) #inSalesforce

Create Record via Inbound Email Object (and using Email Services) #inSalesforce


For every email the Apex email service domain receives, Salesforce creates a separate Inbound Email object that contains the contents and attachments of that email. 

Create Apex classes that implement the Messaging.InboundEmailHandler interface to handle an inbound email message.


Example:

Create Tasks for Contacts. Get contact based on the inbound email address and create a new task.

global class CreateTaskEmailExample implements Messaging.InboundEmailHandler {
 global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, 
                                                       Messaging.InboundEnvelope env){
 Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    String myPlainText= '';
    myPlainText = email.plainTextBody;
    Task[] newTask = new Task[0];
    try {
      Contact vCon = [SELECT Id, Name, Email
        FROM Contact
        WHERE Email = :email.fromAddress
        LIMIT 1];
      newTask.add(new Task(Description =  myPlainText,
           Priority = 'Normal',
           Status = 'Inbound Email',
           Subject = email.subject,
           IsReminderSet = true,
           ReminderDateTime = System.now()+1,
           WhoId =  vCon.Id));
      insert newTask;    
     System.debug('New Task Object: ' + newTask );   
    }
   catch (QueryException e) {
       System.debug('Query Issue: ' + e);
   }
   result.success = true;
   return result;
  }
}


Once the class is created, Setup | Email Services | New Email Service and fill up necessary details | Save | New Email Address button | Fill up details and Save | Now copy the generated Email Address


Testing:

Compose an email keeping in 'To' the newly generated email address(big link) and once the email is sent, verify that the record has been created in salesforce



Reference: https://help.salesforce.com/s/articleView?id=sf.code_inbound_email.htm&type=5

Comments