public function getEncodedMessage(): string
    {
        $output = '';
        $boundary = '--------' . Generators::random();

        foreach ($this->headers as $name => $value) {
            $output .= $name . ': ' . $this->getEncodedHeader($name);
            if ($this->parts && $name === 'Content-Type') {
                $output .= ';' . self::EOL . "\tboundary=\"$boundary\"";
            }
            $output .= self::EOL;
        }
        $output .= self::EOL;

        $body = $this->body;
        if ($body !== '') {
            switch ($this->getEncoding()) {
                case self::ENCODING_QUOTED_PRINTABLE:
                    $output .= \quoted_printable_encode($body);
                    break;

                case self::ENCODING_BASE64:
                    $output .= \rtrim(\chunk_split(\base64_encode($body), self::LINE_LENGTH, self::EOL));
                    break;

                case self::ENCODING_7BIT:
                    $body = \preg_replace('#[\x80-\xFF]+#', '', $body);
                // break intentionally omitted

                case self::ENCODING_8BIT:
                    $output .= \str_replace(["\x00", "\r", "\n"], ['', '', self::EOL], $body);
                    break;

                default:
                    throw new RuntimeException('Unknown encoding.');
            }
        }

        if ($this->parts) {
            if (\substr($output, -\strlen(self::EOL)) !== self::EOL) {
                $output .= self::EOL;
            }
            foreach ($this->parts as $part) {
                $output .= '--' . $boundary . self::EOL . $part->getEncodedMessage() . self::EOL;
            }
            $output .= '--' . $boundary . '--';
        }

        return $output;
    }