Drupal 8 sending custom html mailers

Many of developers faced situation where you have to send custom html formatted emails from Drupal 8 website. But by default Drupal strips html content from email template.

In websites depending on branding requirement there will be multiple emails need to be send to customers with different lay outs. For example if you are creating contact form you need to send a html email to customers which include images and graphic elements to show details in awesome way.

Also another example the same website have an subscribe form when customers subscribed we need to send a confirmation email to customer email which have confirmation message with services offered by website owner represented in rich graphics including images and buttons and links to other pages.

Normally you will be sending through your custom modules. So by default Drupal strips all html tags and sends mail as plain text. Here we going to set up email system in which you can send multiple custom HTML templates as emails.

Here in step by step we are setting custom modules and latter writing code to send emails with templates.
Make sure smtp server is configured in your server and confirm test mails are sending from Drupal.

Before going to coding part of sending custom HTML mail we have to do some configuration and enable some modules in order to avoid striping HTML tags by Drupal system.

Below are the configurations that we are going to do.

  • Install and configure Mail system module
  • Install and configure Mime Mail module

Mail system module

Install and enable Mail system module

https://www.drupal.org/project/mailsystem

Provides an Administrative UI and Developers API for managing the used mail backend/plugin.
you can see configuration of mail system in below menu path.

Configuration – > System -> Mail System

Confirm below configurations are enabled in mail system

Mime Mail Module

Now we need to install below module which enable to send HTML mails.

Without this if you send emails , Drupal will remove all html tags and send mail as plain text.

We can download this module from below URL.

https://www.drupal.org/project/mimemail

Download module and place in contrb folder of project folder

Click on Extend on menu which will display all  modules and enable mimeemail module , hit install button.

Configuring Mime Mail module

After installation complete, go to Mail system as given below

 

Configuration – > System -> Mail System

 

You can see  module specific configurations in this page.Say YOUR_MODULE is your custom module name.

Select YOUR_MODULE   from drop down you can add multiple modules from where you want to send customized template emails.

Then from Sender Plugin Drop down select  mimeemail

Fromatter plugin keep it as default.

Then Click Add  and save configurations.

Go to below menu and confirm drop down selected as Basic HTML.

Configuration – > System ->mimeemail

Drop down should be selected as Basic HTML

Now All configurations done for sending custom HTML emails without stripping html  elements.  Now we are  going to prepare code for sending multiple emails with different email templates from a custom module.

Now we are going to prepare code to send mails. We group these mail to below steps.

  • Prepare custom PHP template file
  • hook_mail() to define email templates
  • Send the mail using mail manager

 

Custom PHP template file

 Before going to create hook_mail() function here we are creating HTML body of mailer in a separate PHP file and assign to a variable. This will be very help full for managing large email templates indented for marketing purposes.

So if you want to customise HTML template, means not need to edit custom module code every time , you have just edit this php template file and upload it in to the server.

For this purpose we creating folder called mail in theme folder where we are placing php template file.

We are creating a php file which have mail template in an variable . we will use this variable in our hook_mail()

Suppose php fiile name is   campaigner.php . in this initially we will take path of images in theme folder. This image path is used to load images an icons in html template also html template is assigning to a php variable this variable will be used in hook_mail() as message body.

Please see staring part of php code in campaigner.php

Get image paths

global $base_url;
$theme = \Drupal::theme()->getActiveTheme();
$image_url = $base_url.'/'. $theme->getPath();
$img_path = $image_url;
$msg = "YOUR HTML template here";

 

Next we will include this php file in hook mail.

/*=========store template in variable============*/
$msg = '<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Subscription Confirmation</title>
    <!--[if gte mso 9]>
<xml>
  <o:OfficeDocumentSettings>
    <o:AllowPNG/>
    <o:PixelsPerInch>96</o:PixelsPerInch>
 </o:OfficeDocumentSettings>
</xml>
<![endif]-->
</head>

<body style="margin:0px;">
    <table width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#ffffff">
        <tbody>
            <tr>
                <td align="center">
                    <table width="630" border="0" cellspacing="0" cellpadding="0" style="width:630px;">
                        <tr>
                            <td colspan="3" style="line-height:0px;"><img width="1" height="20" alt="" src="'. $img_path.'/modules/mail/images/spacer.gif" /></td>
                        </tr>
                        <tr>
                            <td colspan="3" bgcolor="#cce7f4" style="line-height:0px;"><img width="1" height="15" alt="" src="'.$img_path.'/modules/mail/images/spacer.gif" /></td>
                        </tr>
                        <tr>
                            <td width="15" bgcolor="#cce7f4"><img width="15" height="1" alt="" src="'.$img_path.'/modules/mail/images/spacer.gif" /></td>
                            <td width="600">
                                <table width="600" border="0" cellpadding="0" cellspacing="0" style="width:600px;">
                                    <tbody>
                                        <tr>
                                            <td bgcolor="#e8d9c4" width="600">
                                                <table bgcolor="#fffefe" width="100%" style="border-collapse: collapse;" cellspacing="0" cellpadding="0" border="0">
                                                    <tbody>
                                                        <tr>
                                                            <td colspan="3"><img src="'. $img_path.'/modules/mail/images/banner.jpg" usemap="#logo" alt="offer " /></td>
                                                        </tr>
                                                        <tr>
                                                            <td bgcolor="#fffefe" width="30" align="left" style="line-height:0px;"><img width="30" height="1" alt="" src="'.$img_path.'/modules/mail/images/spacer.gif" /></td>
                                                            <td bgcolor="#fffefe" width="540">
                                                                <table width="100%" bgcolor="#fffefe" style="border-collapse: collapse;" cellspacing="0" cellpadding="0" border="0">
                                                                    <tbody>
                                                                 ---------------
----------------------------------------------
</body>

</html>
';
?>

 

Next we will include this php file in hook mail.

hook_mail() to define email templates

Now we need to implement hook_mail() to define email templates ,  we have to create

Hook function YOUR_MODULE _mail in our custom module here YOUR_MODULE is the name of your custom module.

Please see below hook function

We can create multiple template in  below function using switch statement.

Here we are using ‘form_campaigner’ key for our custom html template.

/**
* Implements hook_mail().
*/
function YOUR_MODULE _mail($key, &$message, $params) {
switch ($key) {
case 'form_advertisement':
-------
break;
case 'form_campigner':
$theme_dirpath = realpath('./').'/'.$GLOBALS['theme_path'];
$f_name = $params['submission']['first_name'];
include("$theme_dirpath/modules/mail/ campaigner.php");
$message['headers']['MIME-Version'] = '1.0';
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
$message['headers']['Content-Transfer-Encoding'] = '8Bit';
$message['headers']['X-Mailer'] = 'Drupal';
$message['headers']['Reply-To'] = $params['first_name'] . '<'.$params['submission']['email'].'>';

$message['headers']['From'] = $message['headers']['Sender'] = ‘yourmail@gmail.com’;

$message['subject'] .=’welcome form’;
$message['body'][] = $msg; // variable from campaigner.php
break;
}
}

Here, the variables $key, $message and params can be described as :

  • $key: An identifier of the mail template.
  • $message: An array to be filled in. Elements in this array include: id, to, subject, body, from, headers
  • $params: An array of parameters supplied by the caller of drupal_mail().

 

Send the mail using mail manager

Now lets create a custom function to send the mail using mail manager.

place this this function in your module and call where ever you want to send an email by passing a key and parameters.

Function  campaign _mail_send($key, $params){
$mailManager = \Drupal::service('plugin.manager.mail');
$module = ‘YOUR_MODULE’;
$to = $params['to'];
$langcode = $params['language'];
// $langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
return $result;
}

 

Now You will receive mails with exact template that you passed.

Conclusion

There are different articles which follows different methods to send emails through Drupal 8. Here I am using same methods with additional modules in order to avoid one common problem , striping of HTML tags while receiving email templates.

You can download a Free Ebook using below link.

Downlod Free Ebook on  Custom html mailers in Drupal




Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy me a Coffee this will be an ispiration for me to write articles like this.

You may also like...