In the below Email body, I need to grab the External Account Id (4891 in the below example), however, that text can be between 4 and 8 characters long.

Once I have the ID I'll find a matching account with the same External ID and stamp that Account on the Case I'm creating.

External Account Id: 4891
ContactName: John
ContactPhoneNumber: (212) 555-3554
WebsiteUrl: http://google
WorkFlow: 26612707

Thoughts? Everything I've found so far tells me to specify the character count but that doesn't work for me here.

  • 2
    What have you tried so far? Sep 16, 2019 at 17:10
  • you can also look for a text between "External Account Id:" and next end of the line. Whatever is inside those, should be an account id
    – kurunve
    Sep 16, 2019 at 17:15

2 Answers 2


Here's the flow you should do:

  • Add a Util method getExternalIdFromEmail with return type String that returns the external id and pass the email body content as the argument
  • Inside the method, Split the email body content with '\n' (newline character) to separate the content into each line.
  • Identify the message line that contains 'External Account Id'
  • Split this line using ':' as the separator
  • You will get two Strings from the above split, one containing the text 'External Account Id' and the other containing the external id
  • Trim the leading and trailing spaces and return the value

private static String getExternalIdFromEmail(String emailContent){

    if(String.isEmpty(emailContent)) return null;

    String externalIdLine;
    String externalId;
    for(String msgBodyLine : emailContent.split('\n')) {
        if(!String.isEmpty(msgBodyLine) && msgBodyLine.containsIgnoreCase('External Account Id')) {
            externalIdLine = msgBodyLine;
    if(externalIdLine != null) {
        externalId = externalIdLine.split(':')[1].trim();       
    return externalId;    
String externalId = myEmailBody
  .substringBetween('External Account Id:','-----')

See String class

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .