protected function parseStream(Swift_OutputByteStream $emailStream)
    {
        $bufferLength = 78;
        $headerData = '';
        $headerBodySeparator = "\r\n\r\n";

        $emailStream->setReadPointer(0);

        // Read out the headers section from the stream to a string
        while (false !== ($buffer = $emailStream->read($bufferLength))) {
            $headerData .= $buffer;

            $headersPosEnd = strpos($headerData, $headerBodySeparator);

            // Stop reading if we found the end of the headers
            if (false !== $headersPosEnd) {
                break;
            }
        }

        // Split the header data into lines
        $headerData = trim(substr($headerData, 0, $headersPosEnd));
        $headerLines = explode("\r\n", $headerData);
        unset($headerData);

        $headers = [];
        $currentHeaderName = '';

        // Transform header lines into an associative array
        foreach ($headerLines as $headerLine) {
            // Handle headers that span multiple lines
            if (false === strpos($headerLine, ':')) {
                $headers[$currentHeaderName] .= ' '.trim($headerLine);
                continue;
            }

            $header = explode(':', $headerLine, 2);
            $currentHeaderName = strtolower($header[0]);
            $headers[$currentHeaderName] = trim($header[1]);
        }

        // Read the entire email body into a byte stream
        $bodyStream = new Swift_ByteStream_TemporaryFileByteStream();

        // Skip the header and separator and point to the body
        $emailStream->setReadPointer($headersPosEnd + strlen($headerBodySeparator));

        while (false !== ($buffer = $emailStream->read($bufferLength))) {
            $bodyStream->write($buffer);
        }

        $bodyStream->commit();

        return [$headers, $bodyStream];
    }