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

    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();



        Lead ld = new Lead();
        ld.Company ='bbc';
        //ld.LastName='Abhi Sinha';   
       // system.Debug('Replacevalue ' + email.plainTextBody.replace('\n',''));
        String[] bodySplitted = email.PlainTextBody.split('\r\n');
        System.debug(bodySplitted +'bodySplitted');
        String firstName = bodySplitted[0].substringAfter(': ');
        System.debug(firstName +'firstName ');
        ld.LastName= bodySplitted[1].substringAfter(': ');

       // System.debug(email.plainTextBody +'TextBody');
        //c.First Name= email.plainTextBody;
        insert ld;



result.success = true;
    return result;
}

Unable to get the field.array out of bound exception

Email body is like this

Firstname: starone1256 Lastname : startwo876

Mr.Frodo
  • 5,804
  • 1
  • 16
  • 37
Abhishek
  • 47
  • 7

3 Answers3

1

Realistically, split isn't the right tool for the job. Instead, consider using a Regular Expression:

public Map<String, String> parseEmailBody(String plainText) {
  Pattern lineMatch = Pattern.compile('(?m)^(.+?): ?(.+?)$');
  Matcher matches = lineMatch.matcher(plainText);
  Map<String, String> result = new Map<String, String>();
  while(matches.find()) {
    result.put(matches.group(1), matches.group(2));
  }
  return result;
}

You parse your email like this:

Map<String, String> inputs = parseEmailBody(email.plainTextBody);
for(String field: key) {
  ld.put(field, inputs.get(field));
}
insert ld;

This allows you to automatically parse out extra fields, too, like email, phone, fax, or even custom fields! You may want to add some error checking on this to make sure the field exists, etc.


Regular Expression Explaination

(?m)                 Enable MULTILINE flag
    ^                Match start of input and after each newline/carriage return
     (               Start capture group 1
      .+?            Match as few characters to satisfy next piece of input (:)
         )           End capture group 1
          :          Match a literal colon
            ?        Match an optional space
             (.+?)   Same as above, capture group 2
                  $  Match end of line/input

From there, we put the matches into a map, then dynamically assign the fields from the map into the lead record.

sfdcfox
  • 489,769
  • 21
  • 458
  • 806
0

It appears to me that you're not processing the inbound email correctly. Here's an example of the proper way to handle an inbound email message:

global class processApplicant implements 
        Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(
        Messaging.InboundEmail email, 
            Messaging.InboundEnvelope envelope)&nbsp;{
        Messaging.InboundEmailResult result = 
            new Messaging.InboundEmailresult();

            return result;
        }   
}

Parse through the incoming email message and look for the required information. For example:

// 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);
crmprogdev
  • 40,955
  • 9
  • 58
  • 115
0

Try this, I am able to get the correct output, consider this format [Firstname: starone111 Lastname: starasda]

String emailBody = email.PlainTextBody;
String fnText = 'Firstname:';
String lnText = 'Lastname:';
Integer fn_startIndex = emailBody.indexOf(fnText);                                                 
Integer ln_startIndex = emailBody.indexOf(lnText);

String firstName = emailBody.substring(fn_startIndex + fnText.length(), ln_startIndex-1);
System.debug('firstName --- ' + firstName);                                           

String lastName = emailBody.substring(ln_startIndex + fnText.length());
System.debug('lastName --- ' + lastName); 

Debug log:

enter image description here

In case if you need to add more text after the user name, to fetch the lastname you need to modify the line, pseudo code

String lastName = emailBody.substring(ln_startIndex + fnText.length(), index of static string or lastname index + length + lastname text length);

please let us know once you test this.

Naveen K N
  • 68
  • 1
  • 1
  • 9