Home > Blog > Email service in Salesforce

Email service in Salesforce

Email service is automated 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 You can use email services to process the contents, headers, and attachments of the inbound email. For example, you can create an email service that automatically creates contact records based on contact information in messages.
  • Visualforce email templates cannot be used for mass email.
You can associate each email service with one or more Salesforce-generated email addresses to which users can send messages for processing. To give multiple users access to a single email service, you can:
  • Associate multiple Salesforce-generated emails address with the email service and allocate those addresses to users.
  • Associate a single Salesforce-generated email address with the email service, and write an Apex class that executes according to the user accessing the email service. For example, you can write an Apex class that identifies the user based on the user’s email address and creates records on behalf of that user.
To use email services, from Setup, enter Email Services in the Quick Find box, then select Email Services.
  • Click New Email Service to define a new email service.
  • Select an existing email service to view its configuration, activate or deactivate it, and view or specify addresses for that email service.
  • Click Edit to make changes to an existing email service.
  • Click Delete to delete an email service.
    • Before deleting email services, you must delete all associated email service addresses.
      When defining email services, note the following:
    1. An email service only processes messages it receives at one of its addresses.
    2. Governance limit of Email services in Salesforce: Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case, can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day, depending on how you configure the failure response settings for each email service. Salesforce calculates the limit by multiplying the number of user licenses by 1,000; maximum 1,000,000. For example, if you have 10 licenses, your org can process up to 10,000 email messages a day.
    3. Email service addresses that you create in your sandbox cannot be copied to your production org.
    4. For each email service, you can tell Salesforce to send error email messages to a specified address instead of the sender’s email address.
    5. Email services reject email messages and notify the sender if the email (combined body text, body HTML, and attachments) exceeds approximately 10 MB (varies depending on language and character set).InboundEmailService :When we get an email from an external system to Salesforce, the apex class will process the emails, attachements& perform requested operation. To perform this you have to write apex class by implementing the “Messaging.InboundEmailHandler” interface. And also there are some predefined classes under Messaging name space to implement this. Below are the predefined classes.1.InboundEmail 2. InboundEmail.Header 3. InboundEmail.BinaryAttachment 4. InboundEmail.TextAttachment 5. InboundEmailResult 6. InboundEnvelope

       The Inbound Email Handler

      For every email the Apex email service domain receives, Salesforce creates a separate InboundEmail object that contains the contents and attachments of that email. You can use Apex classes that implement the Messaging.InboundEmailHandlerinterface to handle an inbound email message. Using the handleInboundEmail method in that class, you can access an InboundEmail object to retrieve the contents, headers, and attachments of inbound email messages, as well as perform many functions. Step-1: An Apex class that acts as an inbound email handler simply needs to implement the Messaging.InboundEmailHandlerinterface. The interface defines a single method: Messaging.InboundEmailResulthandleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope envelope) The message contents are available through the email argument, and the envelope stores the to and from address. Here is an example that shows how you can use these objects to access different fields in the incoming email. This class processes incoming email as follows:
      1. Create a new Account record with the email subject as the account name
      2. Generate contacts based on the names on the cc-list
      3. Save the text and binary attachments
      4. Store the email body as a note
      Step-2: Here’s a walkthrough of the entire class, a few lines at a time: First, the class implements the Messaging.InboundEmailHandler interface and all the action happens in the handleInboundEmail() method. global class EmailDemoReceive implements Messaging.InboundEmailHandler { global Messaging.InboundEmailResulthandleInboundEmail(Messaging.InboundEmail email, Messaging.Inboundenvelope envelope) {  … As a good practice:
      1. Create a result to show whether your processing succeeded or failed. A value of null is taken as a success, but it is better to make this explicit.
      2. Note that we process everything in a try-catch block
          …Account account;Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); try {  Step-3: The email and envelope arguments have several public attributes you can access directly. First, let’s grab the email’s subject and create a new account record if it doesn’t already exist. // Look for account whose name is the subject and create it if necessary if ([select count() from Account where Name = :email.subject] == 0) {account = new Account();account.Name = email.subject;insert account;} else {account = [select Id from Account where Name = :email.subject];} Step-4: Now we’ll process the email addresses in the CC: // Convert cc’d addresses to contacts for (String address : email.ccAddresses) {  Contact contact = new Contact();  Matcher matcher = Pattern.compile(‘<.+>’).matcher(address);   // Parse addresses to names and emailsif (matcher.find()) {String[] nameParts = address.split(‘[ ]*<.+>’)[0].replace(‘”‘, ”).split(‘[ ]+’); contact.FirstName = nameParts.size() > 1 ? nameParts[0] : ”;contact.LastName = nameParts.size() > 1 ? nameParts[nameParts.size()-1] : nameParts[0];contact.Email = matcher.group().replaceAll(‘[<>]’, ”);  } else {contact.LastName = address;contact.Email = address;  } // Add if new if ([select count() from Contact where Email = :contact.Email] == 0) {contact.AccountId = account.Id;insert contact;  }}  Step-5: You can even access text and binary attachments:  // Save attachments, if anyfor (Messaging.Inboundemail.TextAttachmenttAttachment : email.textAttachments) {  Attachment attachment = new Attachment(); attachment.Name = tAttachment.fileName;attachment.Body = Blob.valueOf(tAttachment.body);attachment.ParentId = account.Id;insert attachment;}for (Messaging.Inboundemail.BinaryAttachmentbAttachment : email.binaryAttachments) {  Attachment attachment = new Attachment(); attachment.Name = bAttachment.fileName;attachment.Body = bAttachment.body;attachment.ParentId = account.Id;insert attachment;}  And of course, you can access the body of an email as well. In this case we’re assuming a plain email (not an HTML one) and use the plainTextBody field: // Turn email body into noteNote note = new Note(); note.Title = email.fromName + ‘ (‘ + DateTime.now() + ‘)’;note.Body = email.plainTextBody;note.ParentId = account.Id;insert note;Step-6: Here we explicitly indicate success or failure by setting the success field of our InboundEmailResult object.   …result.success = true;    } catch (Exception e) {result.success = false;result.message = ‘Oops, I failed.’    } return result;  }} If a failure was indicated (if the success field is set to false) then the platform automatically rejects the inbound email and sends a reply email to the original sender containing the message specified in the message field. That’s all it takes! Of course, we’ve written a reasonably complex class here, but there’s really only a single method to implement, and the framework makes all the bits that matter (the email addresses, the email body, the attachments and so on) very easily accessible. How to configure Email Service? Below are the steps to create an email service- step 1. Setup -> Develop -> Email Services
 step 2. Click on New Email Service button .     step 3. Fill the required details like Email Service Name, APexClass and check Active checkbox & click                                         on SaveandNewEmailAddress. See the below image for reference.   STEP 4:- Generate an email address 1) Click on “New Email Address” button.
  1. 2) Then add all below detail3) 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 5:- Testing of email service 1) Create one contact with sender email address. 2) Then send email from given email domain to same email address.  

    Example:-Create Tasks for Contacts

    Here’s a simple class that creates create a new task and attaches any documents to that record. global class CreateTaskEmailExample implements Messaging.InboundEmailHandler {  globalMessaging.InboundEmailResulthandleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelopeenv){  // 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;  // New Task object to be created  Task[] newTask = new Task[0];  // Try to look up any contacts based on the email from the address     // If there is more than one contact with the same email address,     // an exception will be thrown and the catch statement will be called.  try {       Contact vCon = [SELECT Id, Name, Email         FROM Contact         WHERE Email = :email.fromAddress         LIMIT 1];  // Add a new Task to the contact record we just found above.  newTask.add(new Task(Description =  myPlainText,            Priority = ‘Normal’,            Status = ‘Inbound Email’,            Subject = email.subject, IsReminderSet = true, ReminderDateTime = System.now()+1, WhoId=  vCon.Id));  // Insert the new Task  insertnewTask;     System.debug(‘New Task Object: ‘ + newTask );       } // 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 true. No need to send an email back to the user    // with an error message  result.success = true;   // Return the result for the Apex Email Service  return result;   } } Summary: Force.com has all the necessary services to easily handle incoming and outgoing emails. To process the incoming emails, you simply create an inbound email handler, bind it to an email service and an email address, and you are good to go! Hope This blog will help you guys.
Thank you so much!!
Enquire Now
X

lets get over a cup of coffee and discuss!