function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SCRSCR 

How to write a test class for class that implements Messaging.InboundEmailHandler?

I am new to Email Services and Apex and wanting to learn effective methods for testing classes that implement the Messaging.InboundEmailHandler.  Please refer me to any good material for learning test methods and best practices for conducting them.  Please see the class code (ProcessApplicant) and Initial Test method Apex Class.  I'm only getting 16% code coverage using the current test method.

 

Thanks,

SCR

/* * This class implements Message.InboundEmailHandler to accept inbound applications for a given position. * It results in a new Candidate (if one doesnt already exist) and Job Description record being created. * Any binary email attachments are automatically transfered to the Job Description as attachments on the Notes and Attachments related list. */ global class ProcessApplicant implements Messaging.InboundEmailHandler { private static final String PHONE_MATCH = 'Phone:'; global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope envelope) { // Indicates if the message processes successfully, permits an error response to be sent back to the user. Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); try { // Obtain the applicants name and the position they are applying for from the email. String firstName = email.fromname.substring(0,email.fromName.indexOf(' ')); String lastName = email.fromname.substring(email.fromName.indexOf(' ')); String positionName = email.subject; String emailBody = email.plainTextBody; String emailFrom = envelope.fromAddress; // Process the email information. processApplicantEmail(firstName, lastName, positionName, emailBody, emailFrom, email.binaryAttachments); // Success. result.success = true; } catch (Exception e) { // Return an email message to the user. result.success = false; result.message = 'An error occured processing your message. ' + e.getMessage(); } return result; } public static void processApplicantEmail(String firstName, String lastName, String positionName, String emailBody, String emailFrom, Messaging.InboundEmail.BinaryAttachment[] binaryAttachments) { // Obtain the applicants Phone number from the message body. integer phoneMatchIdx = emailBody.indexOf(PHONE_MATCH); if(phoneMatchIdx==-1) throw new ProcessApplicantException('Please state your phone number following Phone: in your message.'); String phoneNumber = emailBody.substring(phoneMatchIdx+PHONE_MATCH.length()); // Resolve the Id of the Position they are applying for. Id positionId; try { // Lookup the Position they are applying for by name. Position__c position = [select Id from Position__c where name = :positionName limit 1]; positionId = position.Id; } catch (Exception e) { // Record not found. throw new ProcessApplicantException('Sorry the position ' + positionName + ' does not currently exist.'); } // Candidate record for the applicant sending this email. Candidate__c candidate; try { // Attempt to read an existing Candidate by email address. Candidate__c[] candidates = [select Id from Candidate__c where email__c = :emailFrom]; candidate = candidates[0]; } catch (Exception e) { // Record not found, create a new Candidate record for this applicant. candidate = new Candidate__c(); candidate.email__c = emailFrom; candidate.first_name__c = firstName; candidate.last_name__c = lastName; candidate.phone__c = phoneNumber; insert candidate; } // Create the Job Application record. Job_Application__c jobApplication = new Job_Application__c(); jobApplication.Position__c = positionId; jobApplication.Candidate__c = candidate.id; insert jobApplication; // Store any email attachments and associate them with the Job Application record. if (binaryAttachments!=null && binaryAttachments.size() > 0) { for (integer i = 0 ; i < binaryAttachments.size() ; i++) { Attachment attachment = new Attachment(); attachment.ParentId = jobApplication.Id; attachment.Name = binaryAttachments[i].Filename; attachment.Body = binaryAttachments[i].Body; insert attachment; } } // Confirm receipt of the applicants email Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setToAddresses( new String[] { emailFrom }); mail.setSubject('Your job application has been received'); mail.setPlainTextBody('Thank you for submitting your resume. Your application will be reviewed to determine if an interview will be scheduled.'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } /* * Represents errors that have occured interpretting the incoming email message */ class ProcessApplicantException extends Exception { } }

 

 

//The ProcessApplicant Test: public class ProcessApplicantTest { public static testMethod void ProcessApplicantTest(){ System.debug('Im starting a method'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); email.subject = 'test'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye'; envelope.fromAddress = 'user@acme.com'; // setup controller object ProcessApplicant catcher = new ProcessApplicant(); catcher.handleInboundEmail(email, envelope); } }

 

Best Answer chosen by Admin (Salesforce Developers) 
thangasan@yahoothangasan@yahoo

Hai Use this

 

 // Success Case
   public static testMethod void ProcessApplicantTest(){
       
       
        // Create a new email, envelope object and Attachment
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
       
        Position__c position = [select Id,name from Position__c limit 1];

        email.subject = position.name;
        email.fromName = 'test test';
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
        Messaging.InboundEmail.BinaryAttachment[] binaryAttachments = new Messaging.InboundEmail.BinaryAttachment[1]; 
        Messaging.InboundEmail.BinaryAttachment binaryAttachment = new Messaging.InboundEmail.BinaryAttachment();
        binaryAttachment.Filename = 'test.txt';
        String algorithmName = 'HMacSHA1';
        Blob b = Crypto.generateMac(algorithmName, Blob.valueOf('test'),
        Blob.valueOf('test_key'));
        binaryAttachment.Body = b;
        binaryAttachments[0] =  binaryAttachment ;
        email.binaryAttachments = binaryAttachments ;
        envelope.fromAddress = 'user@acme.com';
       


        // setup controller object
        ProcessApplicant catcher = new ProcessApplicant();
        Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope);
        System.assertEquals( result.success  ,true);   

   
    }
    // Error Case 1
     public static testMethod void ProcessApplicantTestError1(){
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
        email.subject = 'testSubject';
        email.fromName = 'test';
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
        envelope.fromAddress = 'user@acme.com';

        ProcessApplicant catcher = new ProcessApplicant();
        catcher.handleInboundEmail(email, envelope);

     
     }
    
     // Error Case 2
      public static testMethod void ProcessApplicantTestError2(){
       
       
        // Create a new email, envelope object and Attachment
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
       

        email.subject = 'test';
        email.fromName = 'test test';
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
        envelope.fromAddress = 'user@acme.com';
       


        // setup controller object
        ProcessApplicant catcher = new ProcessApplicant();
        catcher.handleInboundEmail(email, envelope);
   
    }
   
    //Error Case 3
     public static testMethod void ProcessApplicantTestError3(){
       
       
        // Create a new email, envelope object and Attachment
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
       
        Position__c position = [select Id,name from Position__c limit 1];

        email.subject = position.name;
        email.fromName = 'test test';
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye';
        envelope.fromAddress = 'user@acme.com';
       


        // setup controller object
        ProcessApplicant catcher = new ProcessApplicant();
        catcher.handleInboundEmail(email, envelope);
   
    }

 

Thanks

 

Thanga

All Answers

thangasan@yahoothangasan@yahoo

Hai Use this

 

 // Success Case
   public static testMethod void ProcessApplicantTest(){
       
       
        // Create a new email, envelope object and Attachment
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
       
        Position__c position = [select Id,name from Position__c limit 1];

        email.subject = position.name;
        email.fromName = 'test test';
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
        Messaging.InboundEmail.BinaryAttachment[] binaryAttachments = new Messaging.InboundEmail.BinaryAttachment[1]; 
        Messaging.InboundEmail.BinaryAttachment binaryAttachment = new Messaging.InboundEmail.BinaryAttachment();
        binaryAttachment.Filename = 'test.txt';
        String algorithmName = 'HMacSHA1';
        Blob b = Crypto.generateMac(algorithmName, Blob.valueOf('test'),
        Blob.valueOf('test_key'));
        binaryAttachment.Body = b;
        binaryAttachments[0] =  binaryAttachment ;
        email.binaryAttachments = binaryAttachments ;
        envelope.fromAddress = 'user@acme.com';
       


        // setup controller object
        ProcessApplicant catcher = new ProcessApplicant();
        Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope);
        System.assertEquals( result.success  ,true);   

   
    }
    // Error Case 1
     public static testMethod void ProcessApplicantTestError1(){
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
        email.subject = 'testSubject';
        email.fromName = 'test';
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
        envelope.fromAddress = 'user@acme.com';

        ProcessApplicant catcher = new ProcessApplicant();
        catcher.handleInboundEmail(email, envelope);

     
     }
    
     // Error Case 2
      public static testMethod void ProcessApplicantTestError2(){
       
       
        // Create a new email, envelope object and Attachment
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
       

        email.subject = 'test';
        email.fromName = 'test test';
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
        envelope.fromAddress = 'user@acme.com';
       


        // setup controller object
        ProcessApplicant catcher = new ProcessApplicant();
        catcher.handleInboundEmail(email, envelope);
   
    }
   
    //Error Case 3
     public static testMethod void ProcessApplicantTestError3(){
       
       
        // Create a new email, envelope object and Attachment
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
       
        Position__c position = [select Id,name from Position__c limit 1];

        email.subject = position.name;
        email.fromName = 'test test';
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye';
        envelope.fromAddress = 'user@acme.com';
       


        // setup controller object
        ProcessApplicant catcher = new ProcessApplicant();
        catcher.handleInboundEmail(email, envelope);
   
    }

 

Thanks

 

Thanga

This was selected as the best answer
NikhilNikhil

Check this

http://wiki.developerforce.com/index.php/Code_Sample_-_Testing_Email_Services_with_Inbound_Attachments

SCRSCR

Thank both of you very much for your suggestions.  I will use these and let you know the results.

SCR

SCRSCR

Hello - I created a test class using the code example you provided below and addded an additional method from the wiki.  My results:

 

Summary

 
Test ClassProcessApplicantTest
Tests Run5
Test Failures0
Code Coverage Total %83
Total Time (ms)651.0
Class Code Coverage
Class Name                           Coverage %
 
ProcessApplicant                         100
Trigger Code Coverrage
Class Name                           Coverage %
rejectUndereducatedTrigger           75
assignIntervierwers                        31
The test results seem to indicate that the InboundEmailHandler (ProcessApplicant) is working when the test methods are run, but the Email Service does not seem to be handing actual inbound messages.
Mail Client Tests:
Yahoo Mail: I tried using a Yahoo Email account to send in a test email with an attachment that should have created records for Candidate and Job Applicaiton, but it failed and produced the error below:
"An error occured processing your message. Ending position out of bounds: -1"
MS Outlook: I do not get any error message back when using MS Outlook.
Any ideas as to why this is failing?
Thanks for the help.
SCR
SCRSCR

I got the ProcessApplicant class to work in Yahoo Mail, but it won't get any results using MS Outlook.  Is there some explicit way to specify in the class that MS Outlook is the default mail client?

 

Expected Behavior:

Use a VisualForce Page (availablePositions) to allow a Candidate to submit a Job Application with an attached résumé using email that will update or create the appropriate records for a Candidate Object, Job Application Object and a Document list for any attachments (i.e. CV, cover latter, etc.) in the force.com Recruiting application.  I have error messaging set up to catch and throw any error messages either as Apex Messages in the VisualForce Page or as a plain text exception message sent as an error message to the from address on the inbound email. 

 

Actual Behavior:

Click on the 'Apply' link in the VisualForce Page for the job position you are applying for. MS outlook opens up an email message preloaded with the To Address (Email Services inbound address for ProcessApplicant Email Service) subject that is the job position name and default phone text that is required information.

 

Workaround:

Create a new message in my Yahoo Mail account with a To Address set as the inbound email address for ProcessApplicant Email Service, a Subject that has a valid Position Name (i.e. POS-000209), and include a phone number preceded by 'Phone:'.  Everything works as expected, that is a confirmation email is sent from Salesforce, and records are created in the Force.com Recruiting app for Candidate (email sender) and Job Application (for the position applied for) along with any attachments that are stored in the Notes and Attachments related list.

 

I'm not sure why it will not work with MS Outlook.  Any ideas or help is appreciated.

 

Thanks,

SCR

 

Thanks,

SCR

SCRSCR

<apex:page controller="AvailablePositionsController" action="{!init}"> <apex:pageBlock > <apex:sectionHeader title="Available Positions" subtitle="The following positions are currently available"/> <apex:pageBlockTable value="{!positions}" var="position"> <apex:column rendered="{!inboundEmailAddr!=null}"> <apex:facet name="header">Action</apex:facet> <apex:outputLink value="mailto:{!inboundEmailAddr}?subject={!position.Name}&body=Phone: (800) 555-1212">Apply</apex:outputLink> </apex:column> <apex:column > <apex:facet name="header">Job Description</apex:facet> <apex:outputText value="{!position.Job_Description__c}"/> </apex:column> <apex:column > <apex:facet name="header">Programming Languages</apex:facet> <apex:outputText value="{!position.Programming_Languages__c}"/> </apex:column> <apex:column > <apex:facet name="header">Salary Grade</apex:facet> <apex:outputText value="{!position.Salary_Grade__c}"/> </apex:column> <apex:column > <apex:facet name="header">Location</apex:facet> <apex:outputText value="{!position.Location_City_State_Country__c}"/> </apex:column> </apex:pageBlockTable> <apex:messages /> </apex:pageBlock> </apex:page>

 

thangasan@yahoothangasan@yahoo

Hai

 

 Check your Email Service Information ,'Accept Email From' Contains your outlook email Address .

 

Regards

Thanga

SCRSCR

Thanks very much for all of the help.  I revised the test methods you provided in your initial response by adding a few error testing comments to better explain the testing procedures in terms of why and how. Code below.

//The ProcessApplicant Test: public class ProcessApplicantTest { // Success Case: Test that email (Header and Body), envelope (Domain and From info) and attachments are received successfully. public static testMethod void ProcessApplicantTest(){ System.debug('Im testing the methods for a Success Case'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); Position__c position = [select Id,name from Position__c limit 1]; email.subject = position.name; // Sender First Name (FName) and Last Name (LName) are successfully pulled from envelope info. email.fromName = 'FName LName'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:(123)456-7890 Bye'; Messaging.InboundEmail.BinaryAttachment[] binaryAttachments = new Messaging.InboundEmail.BinaryAttachment[1]; Messaging.InboundEmail.BinaryAttachment binaryAttachment = new Messaging.InboundEmail.BinaryAttachment(); binaryAttachment.Filename = 'test.txt'; String algorithmName = 'HMacSHA1'; Blob b = Crypto.generateMac(algorithmName, Blob.valueOf('test'), Blob.valueOf('test_key')); binaryAttachment.Body = b; binaryAttachments[0] = binaryAttachment ; email.binaryAttachments = binaryAttachments ; envelope.fromAddress = 'job-candidate.user@acme.com'; // setup controller object ProcessApplicant catcher = new ProcessApplicant(); Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope); System.assertEquals( result.success ,true); } //Another Success Test with emphasis on MIME type email messages with attachments. public static testMethod void mimeTestMethod() { // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); Position__c position = [select Id,name from Position__c limit 1]; Messaging.InboundEmail.BinaryAttachment inAtt = new Messaging.InboundEmail.BinaryAttachment(); email.subject = position.name; envelope.fromAddress = 'job-candidate.user@acme.com'; // set the body of the attachment inAtt.body = blob.valueOf('test'); inAtt.fileName = 'my attachment name'; inAtt.mimeTypeSubType = 'plain/txt'; email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] {inAtt }; // instantiate the class and test it with the data in the testMethod ProcessApplicant emailServiceObject = new ProcessApplicant(); emailServiceObject.handleInboundEmail(email, envelope); } // Error Case 1: Email with required contact information and only 1 part of the fromName. public static testMethod void ProcessApplicantTestError1(){ System.debug('Im testing the methods for a Error Case 1'); Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); //Testing that subject is not a Position Name email.subject = 'testSubject'; email.fromName = 'Name?'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:(123)456-7890 Bye'; envelope.fromAddress = 'job-candidate.user@acme.com'; ProcessApplicant emailServiceObject = new ProcessApplicant(); emailServiceObject.handleInboundEmail(email, envelope); } // Error Case 2: Email with required contact information and both parts of the fromName without attachments. public static testMethod void noAttachmentTest(){ System.debug('Im testing the methods for a Error Case 2'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); //Subject is not position.name email.subject = 'test'; email.fromName = 'FName LName'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Phone:(123)456-7890 Bye'; envelope.fromAddress = 'job-candidate.user@acme.com'; // instantiate the class and test it with the data in the testMethod ProcessApplicant emailServiceObject = new ProcessApplicant(); emailServiceObject.handleInboundEmail(email, envelope); } //Error Case 3: Email with position.name in the subject, but missing required call back (phone) information. public static testMethod void ProcessApplicantTestError3(){ System.debug('Im testing the methods for a Error Case 3'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); Position__c position = [select Id,name from Position__c limit 1]; email.subject = position.name; email.fromName = 'FName LName'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye'; envelope.fromAddress = 'job-candidate.user@acme.com'; // instantiate the class and test it with the data in the testMethod ProcessApplicant emailServiceObject = new ProcessApplicant(); emailServiceObject.handleInboundEmail(email, envelope); } }

 

RajSharanRajSharan

I'm facing the same problem. I've created an "Email to Lead" class. Due to Campaign constraints, I've had to hardcode that information.

 

My test class is not going past  33%.

 

/**
******************************************************************************
Name : EmailToLeadOrContactTask
Objective : Create Lead or Contact Activity
Input Parameter :
Output Parameter:
Calls :
Called from :
Contact : rsharan@navinet.net
Modification History :-
Created/Modified by Created/Modified Date Purpose
-----------------------------------------------------------------------------
1. Raj Sharan 2/24/2010 - Create class
-----------------------------------------------------------------------------
******************************************************************************
*/

/**
* Email services are automated processes that use Apex classes
* to process the contents, headers, and attachments of inbound
* email.
*/
global class EmailToLeadOrContactTask 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();

// Default is Info

String strOwnerID = 'OwnerInfo'; //MASKED
String strCampaignID = 'CampaignInfo'; //MASKED

// Set CampaignID, UserID, etc. based on the To address

if(env.toAddress.compareTo('abc@123.in.salesforce.com') == 0) {
//System.debug('Compare: ' + env.toAddress.compareTo('abc@123.in.salesforce.com')); //MASKED
strOwnerID = 'Owner2'; //MASKED
strCampaignID = 'Campaign2'; //MASKED
}

// Try to lookup any contacts based on the email from address
Contact[] ContactList = [Select Id, Name, Email
From Contact
Where Email = :email.fromAddress
Limit 1];
if (ContactList.Size() > 0) {
for (Contact contact : ContactList){

// Add Contact to Campaign
CampaignMember newCampaignMember = new CampaignMember(CampaignId = strCampaignID,
ContactId = contact.Id);
// Insert the record
try {
insert newCampaignMember;
//System.debug('New Campaign Member: ' + newCampaignMember.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}

// New Task object to be created
Task newTask = new Task(Description = email.plainTextBody,
Priority = 'Normal',
Status = 'Inbound Email',
Subject = email.subject,
IsReminderSet = true,
ReminderDateTime = System.now() + 1,
WhoId = contact.Id,
OwnerId = strOwnerID);

// Insert the new Task
try {
insert newTask;
//System.debug('New Task Object: ' + newTask.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}
}
}
else {
// If no matching contact found, find if the lead already exists
Lead[] LeadList = [Select Id, Email, ConvertedContactId
From Lead
Where Email = :email.fromAddress
Limit 1];
if (LeadList.Size() > 0) {
for (Lead lead : LeadList){
// Add Lead to Campaign after checking if the Lead was already converted to a Contact
CampaignMember newCampaignMember = new CampaignMember(CampaignId = strCampaignID);
if(lead.ConvertedContactId != null) {
newCampaignMember.ContactId = lead.ConvertedContactId;
}
else {
newCampaignMember.LeadId = lead.Id;
}

// Insert the record
try {
insert newCampaignMember;
//System.debug('New Campaign Member: ' + newCampaignMember.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}

// New Task object to be created - on Lead or on converted Contact
String recordID = null;
if(lead.ConvertedContactId != null) {
recordID = lead.ConvertedContactId;
}
else {
recordID = lead.Id;
}

Task newTask = new Task(Description = email.plainTextBody,
Priority = 'Normal',
Status = 'Inbound Email',
Subject = email.subject,
IsReminderSet = true,
ReminderDateTime = System.now() + 1,
WhoId = recordID,
OwnerId = strOwnerID);


// Insert the new Task
try {
insert newTask;
//System.debug('New Task Object: ' + newTask.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}
}
}
else {
// Retrieves the sender's first and last names
String fName = email.fromname.substring(0,email.fromname.indexOf(' '));
//System.debug('First Name: ' + fName);
String lName = email.fromname.substring(email.fromname.indexOf(' '));
//System.debug('Last Name: ' + lName);

// Parse company name
String strCompany = email.fromAddress.substring(email.fromAddress.indexOf('@') + 1, email.fromAddress.indexOf('.', email.fromAddress.indexOf('@')));
//System.debug('Company Name: ' + strCompany);

Lead newLead = new Lead(Description = 'Subject: ' + email.subject + '\n\nBody:\n' + email.plainTextBody,
FirstName = fName,
LastName = lName,
Company = strCompany,
Email = email.fromAddress,
LeadSource = 'Inbound Email',
OwnerId = strOwnerID);

// Insert the new lead
try {
insert newLead;
//System.debug('New Lead Object: ' + newLead.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}

// Add Lead to Campaign
CampaignMember newCampaignMember = new CampaignMember(CampaignId = strCampaignID,
LeadId = newLead.Id);

// Insert the record
try {
insert newCampaignMember;
//System.debug('New Campaign Member: ' + newCampaignMember.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}
}
}

// Set the result to 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;
}
}

 

 

Test Class

 

static testMethod void emailToContactTaskTestMethod() { Account aData = new Account(Name = 'Test1', OfficeNID__c = '1316585'); insert aData; System.assert(aData.Name == 'Test1'); Contact newContact = new Contact(LastName = 'TestContact', AccountID = aData.Id, Office_NID__c = aData.OfficeNID__c, email = 'TestContact' + '@gmail.com'); insert newContact; System.assert(newContact.Office_NID__c == '1316585'); // Create a new email, envelope object Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); email.subject = 'TestForContact'; email.plainTextBody = 'Test'; env.fromAddress = 'TestContact@gmail.com'; env.toAddress = 'abc@123.in.salesforce.com'; EmailToLeadOrContactTask emailServiceObj = new EmailToLeadOrContactTask(); Messaging.InboundEmailResult result = emailServiceObj.handleInboundEmail(email, env); System.assertEquals(result.success, true); } static testMethod void emailToLeadTestMethod() { Lead newLead = new Lead(LastName = 'TestLead', Company = 'TestCompany', email = 'TestLead' + '@gmail.com'); insert newLead; System.assert(newLead.Company == 'TestCompany'); Campaign aCampaign = new Campaign(Name = 'A Campaign'); insert aCampaign; System.assert(aCampaign.Name == 'A Campaign'); // Create a new email, envelope object Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); email.subject = 'TestForLead'; email.plainTextBody = 'Test'; env.fromAddress = 'TestLead@gmail.com'; env.toAddress = 'abc@123.in.salesforce.com'; EmailToLeadOrContactTask emailServiceObj = new EmailToLeadOrContactTask(); Messaging.InboundEmailResult result = emailServiceObj.handleInboundEmail(email, env); System.assertEquals(result.success, true); } static testMethod void emailToNewLeadTestMethod() { // Create a new email, envelope object Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); email.subject = 'TestForNewLead'; email.plainTextBody = 'Test'; env.fromAddress = 'NewTestLead@gmail.com'; env.toAddress = 'abc@123.in.salesforce.com'; EmailToLeadOrContactTask emailServiceObj = new EmailToLeadOrContactTask(); Messaging.InboundEmailResult result = emailServiceObj.handleInboundEmail(email, env); System.assertEquals(result.success, true); }

 

 

Message Edited by RajSharan on 03-01-2010 02:02 PM
Message Edited by RajSharan on 03-01-2010 02:04 PM
ssrssr
 public class cEMS_pageHeader
	  {
	   public Event_Management_System_cems__c emsHeader{get;set;}
	   public String emsIDHeader{get;set;}
	   public cEMS_pageHeader(){}
	  
	   public Event_Management_System_cems__c getEventDetails()
 	   {
 	   return [SELECT Id, Name, Event_Type_cems__c, Applicant_cems_ref__c, Status_cems__c, Applicant_Date_cems__c, Event_Start_Date_cems__c, Event_ID1_cems__c, Event_End_Date_cems__c, Venue_Province1_cems__c, Venue_Country1_cems__c, Venue_City1_cems__c, Mobile_Phone_No_cems__c, Cost_Center_cems__c, WBS_Code_cems__c, Venue_Address_cems__c, Objectives_cems__c, CreatedDate, Disease1_cems__c, Request_Nominees_cems__c, X2nd_Medical_Approver_cems_ref__c, X1st_Medical_Approver_cems_ref__c, Line_Manager_1_cems_ref__c, F_A_Approver_cems_ref__c, DOA_Line_Manager_Approver_cems_ref__c FROM Event_Management_System_cems__c WHERE Id=:emsIDHeader];
 	   }
 	   public String getApprovarName()
 	   {
 	   try
 	   {
 	   ProcessInstance ApprData = [SELECT status,(SELECT ActorId,Actor.Name, OriginalActorId,OriginalActor.Name,ProcessInstanceId FROM Workitems) FROM ProcessInstance WHERE Status='Pending' AND TargetobjectId = :emsIDHeader LIMIT 1];
 	   List<ProcessInstanceWorkitem> workItem = ApprData.WorkItems;
	   return '(' + WorkItem[0].Actor.Name + ')';
 	   }
 	   catch(Exception ex)
 	   {
 	   return '';
 	   }
 	   }
 	  }