1

in apex code, i would like to extract an email address alone from a text like below. Note: The domain name wont be the same. please share if you have any idea?

Example Text:

Delivery has failed for the below recipient

[email protected]

A problem occurred during the delivery of this message to this e-mail address. Try sending this message again. If the problem continues, please contact your helpdesk.

5
  • A good way for searching for sub strings is the rabin karp algorithm
    – M guy
    Feb 12, 2018 at 13:06
  • Rest of the text is remaining static ?
    – NITHESH K
    Feb 12, 2018 at 13:11
  • No They are also not static... basically.. i want to find a first email address of a email body in Bounce back email. The bounce back email wont be having similar text, it may change based on the domain server.
    – Sab__Dev
    Feb 12, 2018 at 13:14
  • In Short, i am trying to get the wrong email id for which the bounce back happened.
    – Sab__Dev
    Feb 12, 2018 at 13:18
  • Email template should have some delimiter separating the email address , Or Some static content surround By the email address. See below Example , i use the word to extract the email address .
    – NITHESH K
    Feb 12, 2018 at 13:22

2 Answers 2

3

You can try with Regex. You need to use find() and group(). As your text is not static so I used some junk text. Sample code for your reference.

String s = 'agfawig [email protected] klaho;hfwaojfoiskfhnkh enesr eknnw rendafn owen';
    Matcher m = Pattern.compile('[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+').matcher(s);
    while (m.find()) {
        System.debug(m.group());
    }
3
  • Great! its working but i am getting helpdesk email addresses which are present below the body. how can i ignore the other email ids? i need only the first email id. Please help
    – Sab__Dev
    Feb 12, 2018 at 13:43
  • 1
    please refrain from asking follow up question in the comments, and rather post a new question. Thanks
    – glls
    Feb 12, 2018 at 13:48
  • 1
    @Tushar Thank you so much .. it works fine ... this is what i was looking for..
    – Sab__Dev
    Feb 13, 2018 at 4:45
0
//string EmailBody;// get the Email body from from the Mail;

This piece of the code only work for the above email.

string EmailBody = 'Delivery has failed for the below recipient' +
                    '[email protected]' +
                    'A problem occurred during the delivery of this message to this e-mail address. Try sending this message again. If the problem continues, please contact your helpdesk.';
Pattern p = Pattern.compile('(?<=below recipient)(.*)(?=A problem)');
Matcher m = p.matcher(EmailBody);
if (m.find()) 
{
   system.debug(m.group(1)); 
}

Try to run the above code in anonymous window

0

You must log in to answer this question.

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