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
Nelson Chisoko 3Nelson Chisoko 3 

How to create and test APEX code for converting Emails to Leads

Hi Guys

Im trying to do apex code for converting emails to leads. I have configured my classes as follows but I cant seem to test them and in turn the whole thing does not work. Could anyone assist...im new to Apex Development:
/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class EmailReceive implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Lead lead;
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();        
        try {
            //Look for lead whos name is the email and create it if necessary
            if ([select count() from Lead where Name = :email.FromAddress] == 0) {
                    lead = new Lead();
                    lead.LastName = email.FromAddress;
                    lead.Email = email.FromAddress;
                    insert lead;
            } else { //Lead already exists
                lead = [select Id from Lead where Name = :email.FromAddress];
            }            
            result.success = true;
        } catch (Exception e) {
            result.success = false;
            result.message = 'Error processing email...';
        }
        return result;
    }
}
Below is my testing class
@isTest
private class EmailReceiveTest {
    static testMethod void myUnitTest() {
        // Create a new email and envelope object
        Messaging.InboundEmail email  = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        //Create the email body
        email.plainTextBody = 'This should become a note';
        email.fromAddress = 'test@test.com';
        String contactEmail = 'jsmith@salesforce.com';
        email.subject = 'Dummy Account Name 123';
        
        EmailReceive er = new EmailReceive();
        
        Test.startTest();
        Messaging.InboundEmailResult result = er.handleInboundEmail(email, env);
        Test.stopTest();
        
        System.assert (result.success, 'InboundEmailResult returned a failure message');
        
        Lead [] leadDb = [SELECT Id FROM Lead where LastName=:email.FromAddress];
        System.assertEquals (1, leadDb.size(),'Lead was not inserted');
    }
}


 
Yogesh NakhateYogesh Nakhate
Hi Nelson, 
following are the changes I made - 
1) Your query in line 13 was returning NULL.
2) Your Lead creation at lines 14-17 did not contain mandatory field 'COMPANY'.
3) in line 13 you are 'Name' with email.FromAddress and in line 15 , you were editing LastName to contain email.FromAddress.
Please refer the code below - 
 
global class EmailReceive implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {

        Lead lead;

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();       
        try {
            //Look for lead whos name is the email and create it if necessary
            
            List<Lead> leadList = new List<Lead>();

            
            String tempLead = email.FromAddress;
            System.debug('FROMADDRESS = '+email.FromAddress);
            System.debug('FROMADDRESS TEMPLEAD = '+tempLead);

            
            String leadQuery = 'select LastName from Lead where LastName = \'' + tempLead +'\'';
            
            leadList = Database.Query(leadQuery);
            Integer leadCount = leadList.size();
            System.debug('LEAD COUNT FROM THE QUERY -'+leadCount);
            
            if ([select count() from Lead where Name = :email.FromAddress] == 0) {
                    System.Debug('INSIDE IF for LEAD COUNT EQUAL TO 0');
                    lead = new Lead();
                    lead.LastName = email.FromAddress;
                    lead.Company = 'XYZ';
                    lead.Email = email.FromAddress;
                    insert lead;
            } else { //Lead already exists
                lead = [select Id from Lead where Name = :email.FromAddress];
            }           
            result.success = true;
        } catch (Exception e) {
            result.success = false;
            result.message = 'Error processing email...';
        }
        return result;
    }



Create an Email Service to point to the above code. Create a new mail address and send a mail to that newly created mail address to see your code working. And see your lead is created!
David DoldDavid Dold
I modified the code provided here by Yogesh slightly, and would like to make some additional changes.

I have:
 
global class EmailReceive implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {

        Lead lead;

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();      
        try {
            //Look for lead whos name is the email and create it if necessary

            List<Lead> leadList = new List<Lead>();


            String tempLead = email.FromAddress;
            System.debug('FROMADDRESS = '+email.FromAddress);
            System.debug('FROMADDRESS TEMPLEAD = '+tempLead);


            String leadQuery = 'select LastName from Lead where LastName = \'' + tempLead +'\'';

            leadList = Database.Query(leadQuery);
            Integer leadCount = leadList.size();
            System.debug('LEAD COUNT FROM THE QUERY -'+leadCount);

            if ([select count() from Lead where Name = :email.FromAddress] == 0) {
                System.Debug('INSIDE IF for LEAD COUNT EQUAL TO 0');
                lead = new Lead();
                lead.Status = 'New';
                lead.LastName = email.FromName;
                lead.Company = (email.FromAddress.split('@').get(1));
                lead.Email = email.FromAddress;
                lead.Comments_History__c = email.plainTextBody;
                lead.Lead_Source__c = 'sales@';
                insert lead;
            } else { //Lead already exists
                lead = [select Id from Lead where Name = :email.FromAddress];
            }          
            result.success = true;
        } catch (Exception e) {
            result.success = false;
            result.message = 'Error processing email...';
        }
        return result;
    }
}


The lead.Company and lead.LastName don't seem to work and I can't figure out how to get what I want there. Ideally I'd be grabbing domain less the TLD to use as the company name.

In an incredibly ideal world, I'd also be setting the lead.Lead_Source__c as an IF statement based on the to: email address for the incoming email. We'll have sales@ and partners@ and while I could set up a separate service for each, it'd be nice to have a single service that handles both.

Any assistance would be greatly appreciated. I had the service working with the example provided, just trying to make it a bit more directly useful for the team.