Drupal: Gestione semplificata invio mail

In Drupal 7 la gestione mail è flessibile, ma anche un tantino complicata. Sotto una sistema per semplificare l'invio di mail, con alcune features:

  • permette di impostare gli headers velocemente in $params['headers']
  • permette di inviare mail HTML semplicemente impostando l'header Content-Type: text/html [...]

Questo il codice da inserire in un vostro modulo (oppure dentro settings.php):

function drupal_mail_send(&$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'][] = $params['body'];
  if (!empty($params['headers']))
    $message['headers'] = $params['headers'] + $message['headers'];
  //dprint($message);
  
  if (strpos($message['headers']['Content-Type'], 'text/html') !== FALSE) {
    global $conf;
    $conf['mail_system'] = array(
      'default-system' => 'DefaultMailSystem',
      $message['id'] => 'CommonHtmlMailSystem',
    );
  }
}

class CommonHtmlMailSystem implements MailSystemInterface {
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    return $message;
  }

  public function mail(array $message) {
    $mimeheaders = array();
    foreach ($message['headers'] as $name => $value) {
      $mimeheaders[] = $name . ': ' . mime_header_encode($value);
    }
    $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
    return mail(
      $message['to'],
      mime_header_encode($message['subject']),
      // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
      // on Unix and CRLF on Windows. Drupal automatically guesses the
      // line-ending format appropriate for your system. If you need to
      // override this, adjust $conf['mail_line_endings'] in settings.php.
      preg_replace('@\r?\n@', $line_endings, $message['body']),
      // For headers, PHP's API suggests that we use CRLF normally,
      // but some MTAs incorrectly replace LF with CRLF. See #234403.
      join("\n", $mimeheaders)
    );
  }
}

Per inviare una mail è sufficiente usare questo codice all'interno di un vostro modulo:

    ...
    $mail_options = array(
      'subject' => '...',
      'body' => '...',
      'headers' => array (...)
    );
    drupal_mail('MODULE', 'KEY', $target_email, user_preferred_language($target_user), $mail_options, $from, true);
    ...
  function MODULE_mail($key, &$message, $params) {
    switch ($key) {
      case 'KEY':
        drupal_mail_send($message, $params);
    }
  }

Se il vostro modulo non ha particolari esigenze potete anche semplificare l'hook e la chiamata a drupal_mail:

  drupal_mail('MODULE', '', $target_email, user_preferred_language($target_user), $mail_options, $from, true);
  ...
  function MODULE_mail($key, &$message, $params) {
    drupal_mail_send($message, $params);
  }

Commenti

Non ci sono ancora commenti.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I commenti vengono pubblicati dopo la moderazione.