Sara Has No Limits

Good Programmers Evaluate, Simplify, Automate and Document

Receiving and Sending Emails Through Apex

Inbound Email Services

  • Automated process that uses Apex classes to process the content, headers and attachments from inbound emails to a email address.
  • Each email service has one or more salesforce-generated email addresses to which users can send a message for processing.
  • An email service only processes messages it receives at one of it’s addresses. For example, you can create an email service that automatically creates contact records based on contact info in the email message.
  • Your organization is limited in that it can only process (1000 * number of user licenses) messages per day for all email services. Anything above that limit will be bounced, discarded or queued, depending on how the email service was configured.
  • Any target email address that is created in sandbox cannot be deployed to a production org

Setting up Inbound Services

  1. Create the email handler class shell – Basically this is a global class that implements the Messaging.InboundEmailHandler class. You can view a template for creating this class by going to Setup -> Develop -> Email Services
  2. Configure an email service – Click Setup -> Develop -> Email Services -> New Email Service. From here, you enter an Email Service Name, the name of the class you created in step 1, and a type of attachment that will be accepted. You can also specify advanced email security settings to verify the legitimacy of the sending server (such as SPF, SenderId, and DomainKeys)
  3. Complete the email handler class – Will include the following Messaging objects
    • InboundEmail – contains the following:
      •  fromAddress
      •  toAddress
      •  Subject
      •  htmlBody
      • plainTextBody
      •  binaryAttachments
      •  textAttachments
    • InboundEmailResult – returns the result of the email service and sets the success flag in the exception handler class to true if the email delivery was successful
    • InboundEnvelope – stores the envelope or header info associated with the inbound email
    • Handling Attachments – notice that it handles text and binary attachments differently, thus they have to be processed in separate loops.


  4. Configure failure response settings – Determine how the service responds when an attempt to access the email service fails. Some of the actions include the following:
    • Over Email Rate Limit Action – If the limits for all services has reached the daily limit of 1000 * # of user licenses/day
    • Deactivated Email Address Action – If the email address is invalid
    • Deactivated Email Service Action – If the service is inactive
    • Unauthenticated Sender Action – If the authenticated sender checkbox is selected and it fails to authenticate
    • Unauthorized Sender Action – If the users are not listed in the Accept Email From text box
    • Bounce Message – Returns message to sender with a reason for the rejection
    • Discard Message – Deletes the message and does not notify the sender
    • Requeue Message – queues the message for processing in next 24 hours
  5. Generate target email addresses – to do this, do the following:
    1. Click the New Email Address button that opens up the Email Address Information window.
    2. Each salesforce email address is case-sensitive and you only need to specify the local part of the email address, since salesforce will assign the domain name part of the address.
    3. You need to specify a context user that the Apex class will run as
    4. You can also include a list of authorized domains or complete email addresses from where emails can be accepted
  6. Activate service email addresses
  7. Test inbound email

BEST PRACTICE TIP: When testing from a Sandbox, set the Failure Response Settings in Step 4 to “Bounce Message”.

Email Logs

  • Are csv files that can be accessed by clicking Setup -> Monitoring -> Email Log Files. The logs contain the emails sent/received through salesforce along with the email addresses, date/time, delivery status and error codes. But, it does NOT capture the body or attachments of an email.
  • Since developers do not have access to system log files in the context of an inbound email class, they may want to create a custom object to log any exceptions or debug statements.

Outbound Email Services

  • Emails can be written in plain text or HTML format
  • The Messaging.sendEmail method is used to send emails (can send single or mass emails)
  • Email templates can be references to reuse functionality
  • Visualforce pages used as templates provide more template flexibility that the standard email templates
  • sendEmail method returns a sendEmailResult object. This contains two properties:
    • isSuccess, which tells whether the email was accepted
    • sendEmailError , which is a list that contains field names, the text of the error message, status codes, and the ID of the target record

Features of Outbound Emails

  • Org Limits on the number of sendEmail calls include:
    • No more than 10 sendEmails methods for each context (BUT, one call can contain MANY emails and each email can have more than one recipient)
    • All single and mass emails sent from Apex count against the daily mass mail limit and when it is reached, all calls are rejected
  • There are separate limits for emails sent using workflow and approval–related processes, which include:
    • No more than 1000 email alerts per license/per org
    • Daily email limit for overall org is 2 million and when reached, a warning email is sent to default workflow user and system admin
  • No more than 1000 emails can be sent to external email addresses/day
  • The Salesforce user calling the method is automatically inserted into the From Address

TIP: There is no limit to the number of internal emails that can be received. To achieve this, check out the targetObjectID attribute covered in the next section.

Differences Between Single and Mass Emails

  • Both single and mass emails use the following fields:
    • bccSender
    • saveAsActivity
    • useSignature
    • replyTo
    • Subject
    • templateId
    • senderDisplayName
  • But, single emails also use the following:
    • bccAddresses
    • ccAddresses
    • charset
    • documentAttachments
    • fileAttachments
    • htmlBody
    • plainTextBody
    • targetObjectID
    • whatID
    • toAddresses
  • Mass emails specifically use the following:
    • targetObjectIDs (these are the recipients and this field can accept a standard object like Contact, Lead, User)
    • NOTE: By specifying the User object in the targetObjectID field, knows to ignore the 1000 limit and therefore allow the mass email to go to more than 1000 internal users.
    • WhatIDs – This is used in conjunction with the TemplateID

Email Security

  • Emails from Salesforce can be configured to automatically comply with SPF and SenderId security frameworks
  • SPF modifies the From address of an inbound email to a email address to verify it’s legitimacy
  • Enable SenderId compliance to automatically populate the sender field of every email sent from Salesforce with
  • The SenderId compliance enables the receiving mail servers to verify the sender of an email

This post represents a portion of the notes that I took while viewing the Apex Training class, which is part of the Spring 2013 Premier Online Training available from Salesforce. This training class is one of the recommended training courses needed to complete the Salesforce Advanced Developer certification. Go here to get a PDF copy of the entire class notes.

Categories: Developer Certification, Web Services

Tags: , , ,

2 replies

  1. Very Nice and informative article. In addition to this, Salesforce is having limitation of mass emailing:

    I wanted to provide your readers with information about an app called MassMailer which will let salesforce users override salesforce mass email limitations. MassMailer provides two options to send mass emails.
    1. Use mass email wizard similar to Salesforce native mass email wizard that lets you select leads or contacts, Users and a native email template. You can schedule or send now and also track the statistics like opens, clicks, bounces etc.
    2. Use campaign to send mass email to the campaign members without any limits

    So, in order to bypass the mass email limitations, please check the following link:

    Hope it will help to the readers.


    • Thanks Amjad.

      So, I am assuming that you get around the limits by just passing the necessary info off to an external application that then handles the actual mailing? Great idea! I imagine your app will be very successful.

      Thanks for stopping by the blog to tell us about it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 86 other followers