Recipes by Category

App Distribution (2) Bundle logic, interface and services for distribution. App Logic (37) The Apex programming language, workflow and formulas for logic. Collaboration (5) The Salesforce Chatter collaboration platform. Database (29) Data persistence, reporting and analytics. Integration (33) Web Service APIs and toolkits for integration. Security (9) Platform, application and data security. Tools (4) Force.com tooling User Interface (36) Visualforce MVC and metadata-drive user interfaces. Web Sites (12) Public web sites and apps with optional user registration and login.
Beta Feedback
Cookbook Home » Email Recipes—Complete Code Example

Email Recipes—Complete Code Example

Post by Developer Force  (2010-07-16)

Status: Certified
Level: novice
The following Apex code is a complete version of the ProcessApplicant class, containing code from these recipes:
/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * emails.
 */ 
    
global class processApplicant implements 
        Messaging.InboundEmailHandler {

  // Creates new candidate and job application objects  
    
 
Contact[] myContact = new Contact[0];
Candidate__c[] newCandidate = new Candidate__c[0];
Job_Application__c[] newJobApplication = 
        new Job_Application__C[0];

 global Messaging.InboundEmailResult handleInboundEmail(
  Messaging.InboundEmail email, 
  Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = 
        new Messaging.InboundEmailresult();
 
  // Captures the sender's email address  
    
String emailAddress = envelope.fromAddress;
 
  // Retrieves the sender's first and last names  
    
String fName = email.fromname.substring(
        0,email.fromname.indexOf(' '));
String lName = email.fromname.substring(
        email.fromname.indexOf(' '));
 
  // Retrieves content from the email.  
    
  // Splits each line by the terminating newline character  
    
  // and looks for the position of the phone number and city  
    

String[] emailBody = email.plainTextBody.split('\n', 0);
String phoneNumber = emailBody[0].substring(6);
String city = emailBody[1].substring(5);
 
  // Creates a new candidate from the information  
    
  // retrieved from the inbound email  
    
   try
    {
      newCandidate.add(new Candidate__c(email__c = emailAddress,
      first_name__c = fName,
      last_name__c = lName,
      phone__c = phoneNumber,
      city__c = city));
 
      insert newCandidate;
   }
    
   catch (System.DmlException e)
   {
System.debug('ERROR: Not able to create candidate: ' + e);
   }
 
  // Looks for a job name based on the email subject   
    
 // (this example assumes the email subject exactly   
    
 // matches an existing job name)  
    
Position__c pos;
pos = [select ID from Position__c where name =
             :email.subject limit 1];
    ID jobId = pos.ID;
 
 // Associates the candidate with the job application  
    
newJobApplication.add(new Job_Application__c(
        Position__c = jobId,candidate__c = newCandidate[0].id));
 
   insert newJobApplication;

 // Searches the email for binary attachments and   
    
 // associates them with the job application  
    
 
if (email.binaryAttachments != null && email.
            binaryAttachments.size() > 0)
{
for (integer i = 0 ; i < email.binaryAttachments.size() ; i++)
{
Attachment a = new Attachment(ParentId = 
            newJobApplication[0].Id,
Name = email.binaryAttachments[i].filename,
Body = email.binaryAttachments[i].body);
insert a;
  }
 }
 
 // Sends the email response  
    
    myContact = createContact.newContact
            (fName, lName, emailAddress, phoneNumber);
  // Sends an email notification to the applicant  
    
   emailHelper.sendEmail(myContact[0].id, newCandidate[0].id);
 
return result;
    }   
}

  // In a separate class so that it can be used elsewhere
Global class emailHelper {

public static void sendEmail(ID recipient, ID candidate) {

  //New instance of a single email message
 Messaging.SingleEmailMessage mail = 
        new Messaging.SingleEmailMessage();
 
// Who you are sending the email to
mail.setTargetObjectId(recipient);

  // The email template ID used for the email
mail.setTemplateId('00X30000001GLJj');
       
mail.setWhatId(candidate);    
mail.setBccSender(false);
mail.setUseSignature(false);
mail.setReplyTo('recruiting@acme.com');
mail.setSenderDisplayName('HR Recruiting');
mail.setSaveAsActivity(false);  
 
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

  }  
}

Share

Recipe Activity - Please Log in to write a comment

Hi - I have ammended by code 


however Io am gettnig the following error:

 
The attached message was sent to the Email Service address <inbound_email_to_lead@p-5mwzfrm0nxt6p749ki530zlzk.2ntneeac.2.apex.salesforce.com> but could not be processed because the following error occurred:
 
554 System.StringException: Starting position out of bounds: 10
 
Class.CreateLeadfromEmail.handleInboundEmail: line 40, column 1

Any ideas?

Thanks in advance

by Steven Brookes  (2012-11-26)

X

Vote to Verify a Recipe

Verifying a recipe is a way to give feedback to others and broaden your own understanding of the capabilities on Force.com. When you verify a recipe, please make sure the code runs, and the functionality solves the articulated problem as expected.

Please make sure:
  • All the necessary pieces are mentioned
  • You have tested the recipe in practice
  • Have sent any suggestions for improvements to the author

Please Log in to verify a recipe

You have voted to verify this recipe.