Trying to parse an email for custom X-headers

My web developer is really busy, so I’m trying to jump in and see if I can get this figured out. Bounced emails are coming in, and we need to extract the EmailID custom header, which purposely is not prefaced with X- He setup a while loop to parse through the entire body content of the email. For my code example below, I just put one line of what would normally be in the full email, into $bodyContent.


$bodyContent = "EmailID: 12345\r\n";
$separator	= "\r\n";
$line		= strtok($bodyContent, $separator);

while ($line !== false) {			

      if (strpos($line, "EmailID:")) {

        list($lineKey, $extractedHeader) = explode(' ', $line);

      if (strpos($line, "EmailID:")) {

          if (preg_match_all('/<(.*?)>/',$line,$match1)) {         
              $extractedHeader= $match1[1][0];
  $line = strtok( $separator );  // Not sure what this does

// End while loop

$finalEmailID	= preg_replace('~\D~', '', $extractedHeader);

echo $finalEmailID;

How do I go about getting the emailID, which in this case is 12345? Which of the two main IF statements inside the while loop will best do the job?

Thank you!

I would do it like this:

$emailContent = "EmailID: 12345\r\n\r\nBody text";

$headers = explode("\r\n\r\n", $emailContent, 2)[0];

$headerLines = explode("\r\n", $headers);

$emailId = null;
foreach ($headerLines as $line) {
  if (strpos($line, 'EmailID:') === 0) {
    list($emailId) = sscanf($line, 'EmailID: %d');

    // emailId found, not need to scan further headers

if (null === $emailId) {
  // help, no emailId found!

  1. First split email headers from body - you don’t want to be looking for EmailID: in the email body, that doesn’t make sense
  2. Loop over all headers
  3. If a header starts with EmailID: use sscanf to get the ID out of that header
  4. Once an EmailID is found, stop looping, no point trying to find more EmailID in the headers (I think)
1 Like

Thank you @rpkamp for your input. However, when I try to add your simple example to my code it leads to segmentation faults, which are very difficult to troubleshoot because they never state an actual error message or the line number that caused it. Thoughts?

Not really, no. It worked when I tried it :man_shrugging:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.