You are here

public static function MimeMailFormatHelper::mimeMailRfcHeaders in Mime Mail 8

Makes mail message and MIME part headers RFC2822-compliant.

Implements and enforces header field formatting including line length, line termination, and line folding as specified in RFC2822.

Parameters

array $headers: An array of headers where the keys are header field names and the values are the header field bodies.

Return value

string One string containing a concatenation of all formatted header fields, suitable for directly including in an email.

See also

http://tools.ietf.org/html/rfc2822#section-2.2

2 calls to MimeMailFormatHelper::mimeMailRfcHeaders()
MimeMailFormatHelper::mimeMailMultipartBody in src/Utility/MimeMailFormatHelper.php
Builds a multipart body.
MimeMailFormatHelperTest::testRfcHeaders in tests/src/Kernel/MimeMailFormatHelperTest.php
Tests making headers RFC822-compliant.

File

src/Utility/MimeMailFormatHelper.php, line 675

Class

MimeMailFormatHelper
Utility methods for formatting MIME-encoded email messages.

Namespace

Drupal\mimemail\Utility

Code

public static function mimeMailRfcHeaders(array $headers) {

  // Use RFC2822 terminology for all variables - 'header' refers to the
  // collection of all header fields. Each header field is composed of
  // a header field name followed by a colon followed by the header field
  // body, terminated by CRLF.
  $header = '';
  foreach ($headers as $field_name => $field_body) {

    // Header field names should not have leading or trailing whitespace.
    $field_name = trim($field_name);

    // Collapse spaces and get rid of newline characters.
    $field_body = trim($field_body);
    $field_body = preg_replace('/(\\s+|\\n|\\r)/', ' ', $field_body);

    // Fold headers if they're too long.
    // A CRLF may be inserted before any WSP.
    // @see http://tools.ietf.org/html/rfc2822#section-2.2.3
    $header_field = $field_name . ': ' . $field_body;
    if (mb_strlen($header_field) >= static::RFC2822_MAXLEN) {

      // If there's a semicolon, use that to separate.
      if (count($array = preg_split('/;\\s*/', $header_field)) > 1) {
        $header_field = trim(implode(';' . static::CRLF . ' ', $array));
      }

      // Always try to wordwrap.
      $header_field = wordwrap($header_field, static::RFC2822_MAXLEN, static::CRLF . ' ', FALSE);
    }
    $header .= $header_field . static::CRLF;
  }
  return $header;
}