Search code examples
phpregexemail-bounces

RegEx for parsing "Diagnostic-Code" in a bounced e-mail


I'm trying to read bounced e-mails by connecting via PHP to a IMAP account and fetching all e-mails. I'm looking to retrieve the "Diagnostic-Code" message for each e-mail and I wrote the following regex:

/Diagnostic-Code:\s+?(.*)/i

The message that I'm trying to parse is this:

Diagnostic-Code: smtp; 550-5.1.1 The email account that you tried to reach does
    not exist. Please try 550-5.1.1 double-checking the recipient's email
    address for typos or 550-5.1.1 unnecessary spaces. Learn more at 550 5.1.1
    https://support.google.com/mail/?p=NoSuchUser 63si4621095ybi.465 - gsmtp

The regex works partly meaning it only fetches the first row of text. I want to be able to fetch the entire message, so all the four rows of text.

Is it possible to update the expression to do this matching?

Thanks.


Solution

  • /Diagnostic-Code:\s(.*\n(?:(?!--).*\n)*)/i
    
    • result will be in capture group 1
    • first .*\n matches first line including trailing newline
    • (?:(?!--).*\n)* matches subsquent lines that don't begin "--"