3

I want the outgoing mail that is sent by my custom module to be in HTML, but I dont know how.

This is my submit function:

//create an array from the companies in the db in a comma separated list
$companies = db_query("SELECT companies FROM {offer} WHERE id = $id")->fetchField();
$companies = explode(',', $companies);

// Set some variables
$from = 'noreply@danielholm.se';
$subject = 'Sent mail';
$module = 'mymodule';
$key = 'mykey';
$language = language_default();
$params = array();
$send = TRUE;

// the data
$question = db_query("SELECT message FROM {offer} WHERE id = $id")->fetchField();
$name = db_query("SELECT name FROM {offer} WHERE id = $id")->fetchField();
$mail = db_query("SELECT mail FROM {offer} WHERE id = $id")->fetchField();
$phone = db_query("SELECT phone FROM {offer} WHERE id = $id")->fetchField();
$compname = db_query("SELECT compname FROM {offer} WHERE id = $id")->fetchField();
$comptype = db_query("SELECT comptype FROM {offer} WHERE id = $id")->fetchField();

// Sort the companies
foreach($companies as $company) {
        $message = drupal_mail($module, $key, $company, $language, $params, $from, $send);
        // Create the mail content
        $message['subject'] = $subject;
        $message['body'] = array();
$message['body'][] = 'THe HTML MAIL HERE';

        // Retrieve the responsible implementation for this message.
        $system = drupal_mail_system($module, $key);

        // Format the message body.
        $message = $system->format($message);

        // Send e-mail.
        $message['result'] = $system->mail($message);

        // Update table where sent to 1
        $update = db_update('offer')
            ->fields(array(
            'sent' => '1',
            ))
            ->condition('id', $id, '=')
            ->execute();

        // Set message of performed action
        drupal_set_message('Done');
        $form_state['redirect'] = 'admin/content/offer';
        cache_clear_all();
}
  • There is a function named user_load($uid) to load all user fields in Drupal.. ;) – niksmac Nov 4 '12 at 9:57
9

drupal_mail() by default adds text/plain headers. You have 3 options here:

  1. use Hook_mail_alter and add your custom text/html headers;
  2. use custom pre-build modules mentioned already here;
  3. Implement MailSystemInterface and send you own mail as follows:

class YourMailSystem implements MailSystemInterface {

/**
 * Concatenate and wrap the e-mail body for plain-text mails.
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 *
 * @return
 *   The formatted $message.
 */
public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);

    if ($message['module'] == 'your_module') {
        $body =  $message['body'];
        $message['body'] = array();

        // Convert any HTML to plain-text.
        $message['body']['plain'] = drupal_html_to_text($body);
        $message['body']['plain'] = drupal_wrap_mail($message['body']['plain']);

        // Wrap the mail body for sending.
        $message['body']['html'] = drupal_wrap_mail($body);
    } else {
        $message['body'] = drupal_wrap_mail($message['body']);
    }

    return $message;
}

/**
 * Send an e-mail message, using Drupal variables and default settings.
 *
 * @see <a href="http://php.net/manual/en/function.mail.php
  " title="http://php.net/manual/en/function.mail.php
  " rel="nofollow">http://php.net/manual/en/function.mail.php
  </a>   * @see drupal_mail()
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 * @return
 *   TRUE if the mail was successfully accepted, otherwise FALSE.
 */
public function mail(array $message) {
    $mimeheaders = array();

    if ($message['module'] == 'your_module') {
        $separator = md5(time());
        // carriage return type (we use a PHP end of line constant)
        $eol = PHP_EOL;

        // main header
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = $message['from'];
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = $message['from'];
        $message['headers']['Content-Type'] = "multipart/alternative; boundary=\"".$separator."\"";

        // message
        $body = "--".$separator.$eol;
        $body .= "Content-Type: text/plain; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['plain'].$eol;

        // message
        $body .= "--".$separator.$eol;
        $body .= "Content-Type: text/html; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['html'].$eol;
        $body .= "--".$separator."--";

        foreach ($message['headers'] as $name => $value) {
            $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);

        $sendM = mail(
                $message['to'], mime_header_encode($message['subject']),
                preg_replace('@\r?\n@', $line_endings, $body),
                join("\n", $mimeheaders)
        );

        return $sendM;
    } else {
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = $message['from'];
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = $message['from'];
        $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';

        if(isset($message['customMode']) && $message['customMode'] == 1) {
            $message['headers']['Content-Type'] = 'text/plain; charset=UTF-8; format=flowed; delsp=yes';
        }

        foreach ($message['headers'] as $name => $value) {
            $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        $heads = join("\n", $mimeheaders);

        $sendM = 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.
                $heads
        );

       return $sendM;
    }
  }
}

Then in your module you need to implement a mailSystem usage like so:

  function hook_install() {
      variable_set('mail_system', array_merge(
                      variable_get('mail_system', array('default-system' => 'DefaultMailSystem')), // Previously set mail_system variable
                      array('your_module' => 'YourMailSystem')   // My new key(s) which ADD to the previous keys
              )
      );
  }

  function hook_uninstall() {
      // Unset module keys in variable mail_system
      $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
      unset($mail_system['your_module']);
      variable_set('mail_system', $mail_system);
  }

    function hook_mail($key, &$message, $params) {
      global $language;
        // We can define more then one email template, naming is by key
        //global $language;
        switch ($key) {
          case 'registration':
              // note: data can be passed to this function in the $params array
              $body = ''; // GET YOUR BODY CONTENT
              $subject = ''; // YOUR SUBJECT HERE

              break;
          case 'remind_pass':
              // note: data can be passed to this function in the $params array
              $body = ''; // GET YOUR BODY CONTENT
              $subject = ''; // YOUR SUBJECT HERE

              break;
        }

        $message['subject'] = $subject;
        $message['body'] = array();
        $message['body'][] = '<html><body>';
        $message['body'][] = $body;
        $message['body'][] = '</body></html>';
        return $message;
    }

And to use this mailSystem, call drupal_mail from your module like this:

drupal_mail('your_module', 'remind_pass', 'someone@somewhere.com', language_default(), $params, 'from@mail.com', true);

Things to note: This implementation will send multiple email types, that is: plain and html at once. We could also further improve this to support attachments.

This implementation looks for my custom module content to process as plain/html, if it does not get one, then it sends all stuff as default: text/plain.

11

You can try Mime Mail module.

This is a Mime Mail component module (for use by other modules).

  1. It permits users to recieve HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
  2. If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment.
  3. Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format
  4. If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative.
  5. Allows you to theme messages with a specific mailkey.
  6. Converts CSS styles into inline style attributes.
  7. Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.
  • Thank you. I went with this module. I just installed it, together with mail system, and set it up to use full HTML and that was it. Now my custom mail looks exactly like they should. – Daniel Holm Apr 17 '12 at 19:01
5

I've written a module (which bridges Drupal with the Swift Mailer PHP library) which handles HTML, attachments, inline images, theming and the like. It let's you define wether e-mails by default should be sent as HTML or plain text.

It's currently awaiting approval, but I'm using it myself on production sites and it works well. Have a look at it on http://drupal.org/sandbox/sbrattla/1163884.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.