You are here

public static function MimeMailFormatHelper::mimeMailHeaders in Mime Mail 8

Gives useful defaults for standard email headers.

Parameters

array $headers: Message headers.

string $from: The address of the sender.

Return value

array Overwritten headers.

2 calls to MimeMailFormatHelper::mimeMailHeaders()
MimeMail::prepareMessage in src/Plugin/Mail/MimeMail.php
Prepares the message for sending.
MimeMailFormatHelperTest::testHeaders in tests/src/Kernel/MimeMailFormatHelperTest.php
Tests the regular expression for extracting the mail address.

File

src/Utility/MimeMailFormatHelper.php, line 718

Class

MimeMailFormatHelper
Utility methods for formatting MIME-encoded email messages.

Namespace

Drupal\mimemail\Utility

Code

public static function mimeMailHeaders(array $headers, $from = NULL) {

  /** @var \Drupal\Core\Config\ImmutableConfig $site_config */
  $site_config = \Drupal::config('system.site');

  // Overwrite standard headers.
  if ($from) {
    $default_from = $site_config
      ->get('mail');
    if (!isset($headers['From']) || $headers['From'] == $default_from) {
      $headers['From'] = $from;
    }
    if (!isset($headers['Sender']) || $headers['Sender'] == $default_from) {
      $headers['Sender'] = $from;
    }

    // This may not work. The MTA may rewrite the Return-Path.
    if (!isset($headers['Return-Path']) || $headers['Return-Path'] == $default_from) {
      if (preg_match('/[a-z\\d\\-\\.\\+_]+@(?:[a-z\\d\\-]+\\.)+[a-z\\d]{2,4}/i', $from, $matches)) {
        $headers['Return-Path'] = "<{$matches[0]}>";
      }
    }
  }

  // Convert From header if it is an array.
  if (is_array($headers['From'])) {
    $headers['From'] = static::mimeMailAddress($headers['From']);
  }

  // Run all headers through mime_header_encode() to convert non-ASCII
  // characters to an RFC compliant string, similar to drupal_mail().
  foreach ($headers as $field_name => $field_body) {
    $headers[$field_name] = Unicode::mimeHeaderEncode($field_body);
  }
  return $headers;
}