WP Mail via SMTP in your own HTML template, without a plugin

Without a doubt, WordPress offers by default a lot of possibilities and ranks among the most flexible CMS in the world. Beyond that WordPress can be complemented and changed very well according to the own needs. However, change is often asked for the emails that are sent by the system, since the internal function WP Mail only sends plain emails, but today most clients support HTML emails.

Unfortunately, it is not yet possible to use all elements available for Internet pages, but with the correct structure you can obtain stunning results and adapt the emails very similar to your own Internet presence. This article shows you how to use WP Mail with SMTP. It is also explained how you integrate it into your own HTML templates, with a fallback to plain emails when HTML is disabled at the recipient. As a bonus, you get the info, how you change the HTML Template depending on the subject. All this without additional plugins.

Create an HTML template for WP Mail

Of course, there are different ways to get an HTML template to use it for your WP Mail customizations. One way is to buy an appropriate template from a premium provider. Here, however, you should definitely check the compatibility with the respective email clients.

But with a bit of HTML knowledge, it is quite easy to create your own template. Below is shown how such a template can look like. This template is also available and ready for download. You can customize and use it on your own pages, or your customer’s pages. It is a responsive template, which is also very well presented on mobile devices and can be integrated very easily into WP Mail.

In order to adapt it to your own needs, you just need to open the downloaded HTML file in a browser. Then you can change the file in a text editor of your choice according to your desires. The results can be viewed directly in the browser when you reload it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0;">
  <head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta name="format-detection" content="telephone=no" /> <!-- disable auto telephone linking in iOS -->

    <title>Company Name | CEO: Name Lastname</title>
    <style type="text/css">

      html { margin:0; padding:0; }
      img { max-width: 100%; height: auto; }
      body { -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; width: 100% !important; height: 100%; line-height: 1.6; }
      body { background-color: #ffffff; }
      @media only screen and (max-width: 640px) {
        h1 { font-size: 16px !important; font-style: normal; font-weight: 600; }
        h2 { font-size: 14px !important; font-style: normal; font-weight: 600; }
        h3 { font-size: 12px !important; font-style: normal; font-weight: 600; }
        .content { padding: 10px !important; }
        h1.content { padding: 0px !important; }
        .content-wrapper { padding: 10px !important; }
        /*.headlinks span { display: none; }
        .headlinks a { display: block !important; font-size: 11px !important; }*/
      }
    </style>
  </head>
  <body style="font-family: 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; -webkit-font-smoothing: antialiased; height: 100%; line-height: 1.6; margin: 0px; padding: 0px; width: 100% !important; background: #ffffff;" cz-shortcut-listen="true">
    <p>&nbsp;</p>
    <!-- [if gte mso 9]>
    <table width="650" align="center"><tr>
    <td width="650">
    <![endif]-->
    <table class="body-wrap" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; width: 100%; background: #ffffff; margin: 0; padding: 0;">
      <tbody>

        <tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0;">
          <td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; vertical-align: middle; margin: 0; padding: 0;" valign="middle"> </td>
          <td class="container" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; vertical-align: middle; display: block !important; max-width: 650px !important; clear: both !important; margin: 0 auto; padding: 0;" valign="middle">
            <div class="content" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; max-width: 650px; display: block; margin: 0 auto; padding: 20px; padding-top: 10px;">
              <table class="main" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; background: #ffffff; margin: 0; padding: 0; border: 1px solid #7797a1;" width="100%" cellspacing="0" cellpadding="0">
                <tbody>

                  <tr>
                    <td style="padding: 20px; background: #7797a1;" colspan="2" valign="top"><a href="https://your-domain.com/"> <img src="https://cdn.indikator-design.com/wp-content/uploads/images/blogs/wp-mail/logo.png" alt="Your Company" align="top" width="201" height="57" /></a></td>
                  </tr>

                  <tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0;">
                    <td class="content-wrap" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; vertical-align: middle; margin: 0; padding: 20px;" valign="middle">
                      <table style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0;" width="100%" cellspacing="0" cellpadding="0">
                        <tbody>
                          <tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0;">
                            <td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; vertical-align: middle; margin: 0; padding: 0;" valign="middle">
                              <p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; text-align: center; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0; color: #7797a1;">You receive this email in connection with %reason%. If this is not desired, or if you have not initiated it, please inform us about the contact details below.</p>
                              <h1 style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 18px; margin: 0; padding: 5px; margin-bottom: 10px; margin-top: 20px; text-align: center; background-color: #ffffff; color: #b7a46d;">Your message from Company Name</h1>
                              <br />

                              <table id="content" style="border-collapse: collapse; width: 100%;" cellspacing="0" cellpadding="6">
                                <tbody>
                                  <tr>
                                    <td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; color: #7797a1; font-size: 12px; text-align: left; vertical-align: middle; word-wrap: break-word;">
                                      <div style="float: left; width: 100%;">%content%</div>
                                    </td>
                                  </tr>
                                </tbody>
                              </table>
                              <table style="border-collapse: collapse; width: 100%;" cellspacing="0" cellpadding="6">
                                <tbody>
                                  <tr>
                                    <td width="100%" height="10"> </td>
                                  </tr>
                                </tbody>
                              </table>

                              <div class="email-credentials">
                                <table style="border-collapse: collapse; width: 100%;" cellspacing="0" cellpadding="6">
                                  <tbody>
                                    <tr>
                                      <td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; color: #7797a1; font-size: 12px; text-align: left; vertical-align: middle; word-wrap: break-word;" width="100%">
                                        <div style="float: left; width: 100%;">
                                          <h3 style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0; color: #7797a1;">Imprint</h3>
                                          <p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0; color: #7797a1;"> </p>
                                          <p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0; color: #7797a1;">Company Name | CEO: Name Lastname | Streetname 1 | 12345 City</p>
                                          <p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0; color: #7797a1;">Phone: <a style="color: #7797a1;" href="tel:+49123456789101112">+49 (0) 12345 – 678 910 1112</a><br>
                                          E-Mail: <a style="color: #7797a1;" href="mailto:mail@your-domain.com">mail@your-domain.com</a> | Imprint Website</strong>: <a style="color: #7797a1;" title="Company Name Imprint" href="https://your-domain.com/imprint/">Company Name Imprint</a></p>
                                        </div>
                                      </td>
                                    </tr>
                                  </tbody>
                                </table>

                                <table class="whitespace" style="border-collapse: collapse; width: 100%;" cellspacing="0" cellpadding="6">
                                  <tbody>
                                    <tr>
                                      <td width="100%" height="10"> </td>
                                    </tr>
                                  </tbody>
                                </table>
                                <div class="email-social">
                                  <table style="border-collapse: collapse; width: 100%;" cellspacing="0" cellpadding="6">
                                    <tbody>
                                      <tr>
                                        <td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; vertical-align: middle; text-align: center; width: 100%; margin: 0; padding: 10px 0;" align="center" valign="middle" width="100%">
                                        <a href="https://www.facebook.com/"><img src="https://cdn.indikator-design.com/wp-content/uploads/images/blogs/wp-mail/network.jpg" alt="" border="0" /></a>
                                        <a href="https://plus.google.com/"><img src="https://cdn.indikator-design.com/wp-content/uploads/images/blogs/wp-mail/network.jpg" alt="" border="0" /></a>
                                        <a href="https://twitter.com/"><img src="https://cdn.indikator-design.com/wp-content/uploads/images/blogs/wp-mail/network.jpg" alt="" border="0" /></a>
                                        <a href="http://www.youtube.com/"><img src="https://cdn.indikator-design.com/wp-content/uploads/images/blogs/wp-mail/network.jpg" alt="" border="0" /></a>
                                        <a href="http://www.flickr.com//"><img src="https://cdn.indikator-design.com/wp-content/uploads/images/blogs/wp-mail/network.jpg" alt="" border="0" /></a></td>
                                      </tr>
                                    </tbody>
                                  </table>
                                </div>
                              </div>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </td>
                  </tr>
                </tbody>
              </table>
              <div class="footer" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; width: 100%; clear: both; color: #666; margin: 0; padding: 0;">
                <table style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0;" width="100%">
                  <tbody>
                    <tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0;">
                      <td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 11px; color: #7797a1; vertical-align: middle; text-align: center; width: 100%; margin: 0; padding: 10px 5px; line-height: 1.2;" align="center" valign="middle" width="100%">
                        <p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0; color: #7797a1;">© Company Name | CEO: Name Lastname <br />Contact: <a style="color: #7797a1;" href="https://your-domain.com/contact/">https://your-domain.com/contact/</a><br />%date%</p>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </td>
          <td style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; vertical-align: middle; margin: 0; padding: 0;" valign="middle"> </td>
        </tr>
      </tbody>
    </table>
    <!-- [if gte mso 9]>
  </td></tr></table>
    <![endif]-->
    <p>&nbsp;</p>
  </body>
</html>
You receive this email in connection with %reason%. If this is not desired, or if you have not initiated it, please inform us about the contact details below. 


Your message from Company Name 



%content% 



Imprint
Company Name | CEO: Name Lastname | Streetname 1 | 12345 City 
Phone: +49 (0) 12345 – 678 910 1112 | E-Mail: mail@your-domain.com | Website: https://your-domain.com/imprint/ 

© Company Name | CEO: Name Lastname 
Contact: https://your-domain.com/contact/ | Imprint Website: https://your-domain.com/imprint/ 
%date%

Download the Email-Templates

Within this template, you will find various placeholders surrounded by “%”, such as “%content%”. You can add such areas as many as you need inside your template. These elements can be exchanged dynamically with your desired WordPress information before the emails are sent with WP Mail.

If this is done and you are satisfied with the result, then this template still has to be stored in a PHP variable to continue working with it.

Create the PHP wrapper files for WP Mail

Create now a new folder named “template” in your child theme root. Put two PHP files into this folder: “email-wrap-default-html.php” and “email-wrap-default-plain.php”. As the names already suggest, we use the first file for the HTML template and the second file as a fallback for the plain email.

<?php

if ( ! defined( 'ABSPATH' ) ) exit( __( 'Don\'t try to load this file directly!' ) );

$emailWrapperHTML = <<<MAIL

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 12px; margin: 0; padding: 0;">
  <head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

....

      <div style="float: left; width: 100%;">%content%</div>

....

  </body>
</html>

MAIL;
 
<?php

if ( ! defined( 'ABSPATH' ) ) exit( __( 'Don\'t try to load this file directly!' ) );

$emailWrapperPlain = <<<MAIL

You receive this email in connection with %reason%. If this is not desired, or if you have not initiated it, please inform us about the contact details below. 


Your message from Company Name 



%content% 



Imprint
Company Name | CEO: Name Lastname | Streetname 1 | 12345 City 
Phone: +49 (0) 12345 – 678 910 1112 | E-Mail: mail@your-domain.com | Website: https://your-domain.com/imprint/ 

© Company Name | CEO: Name Lastname 
Contact: https://your-domain.com/contact/ | Imprint Website: https://your-domain.com/imprint/ 
%date%

MAIL;
 

Thus we have inserted both templates for use in WP Mail into the two variables “$emailWrapperHTML” and “$emailWrapperPlain”. Be careful and note the correct spelling of the Heredocs, particularly the blank line after the closing identifier.

If you want to work with different emails, you can now create your files for each case. Always use the same names for the template-variables within the files. Change only the file names themselves and customize the templates inside this files according to your needs. For example, if you want to use a different template for the comments, then you could name two files like this: “email-wrap-comment-html.php” and “email-wrap-comment-plain.php”.

Maybe you’re wondering now why it might make sense to use different templates. There are good reasons for this. Perhaps you use advertising in your default emails or link to blog posts. However, such content should not be used in the emails for the double opt-in for your comments, because in such emails you should not integrate any advertising at all. This can otherwise be cautioned, which can be very expensive under certain circumstances.

WP Mail and PHP-Mailer – activate SMTP

WordPress uses the PHP-Mailer class to send the system emails via WP Mail. You can use the hook “phpmailer_init” to intercept the transmission process and adapt it to your own requirements. But this only works for emails sent with the function “wp_mail”.

The procedure described here can not be used, for example, for WooCommerce emails, since WooCommerce uses its own system. But of course, you can add the different elements of the template used here to the WooCommerce templates, to get a uniform look.

To control the sending process with your settings, simply add the following snippet into your “wp-config.php” and supplement it with your data.

<?php

if ( ! defined( 'ABSPATH' ) ) exit( __( 'Don\'t try to load this file directly!' ) );

add_action( 'phpmailer_init', function( $phpmailer )
{
  include( 'templates/email-wrap-default-html.php' );
  include( 'templates/email-wrap-default-plain.php' );

  $phpmailer->Priority   = 3;
  $phpmailer->Mailer     = 'smtp';
  $phpmailer->From       = 'mail@your-domain.com';
  $phpmailer->FromName   = 'Your Company Name';
  $phpmailer->Sender     = $phpmailer->From;
  $phpmailer->Host       = PREFIX_MAIL_HOST;
  $phpmailer->SMTPSecure = 'ssl';
  $phpmailer->Port       = 465;
  $phpmailer->SMTPAuth   = true;
  $phpmailer->Username   = PREFIX_MAIL_USER;
  $phpmailer->Password   = PREFIX_MAIL_PSWD;
  $phpmailer->AddReplyTo('mail2@your-domain.com',$phpmailer->FromName);

  $reason   = 'Your Message from Company Name | CEO: Name Lastname';
  $date     = 'From '.date_i18n( get_option( 'date_format' ) ).' at '.date_i18n( get_option( 'time_format' ) );

  $search  = [ '%content%', '%reason%', '%date%' ];
  $replace = [ $phpmailer->Body, $reason, $date ];

  $message    = str_replace( $search, $replace, $emailWrapperHTML );
  $messageAlt = str_replace( $search, $replace, $emailWrapperPlain );

  $phpmailer->Body    = $message;
  $phpmailer->AltBody = $messageAlt;
}); // end add_action

Here you hook now into the action “phpmailer_init”, to edit the PHP-Mailer object directly. As you may notice, this object is passed by reference, so “add_action” is used instead of “add_filter”. Here the previously created wrapper files are also inserted, whereby the template variables are available. After this, the SMTP access is initiated, and the account details are assigned. To do this, first, place your desired email in your email administration. It may be useful to link this email address to an autoresponder if you do not want replies to this email.

Now it will be interesting. The date and time are passed to the “$date” variable. In the variable “$reason”, you can specify a reason for the email. Then an array with the values to be exchanged is created and an array with the associated values. The variable “$message” and “$messageAlt” are used to pass the email content, whereby “$messageAlt” is needed for the alternative plain message.

At first, the corresponding email templates are assigned. Thereafter the “%content%” placeholder string is exchanged with the original message “$phpmailer->Body”. The date and time from the variable “$date” are added to replace the placeholder string “%date%” and your desired “$reason” changes the string “%reason%”. Finally, the completed HTML email is added to the “$PHP-Mailer->Body” and the alternative with the pure text content to “$PHP-Mailer->AltBody”.

Use WP Mail and PHP-Mailer with Conditionals

As mentioned before, I show you here also the usage with Conditionals. You can use “if else” queries, or you can choose to use a “switch”. That depends in detail on the number of inquiries. Here in the example, this is shown with a single query and the subject “$phpmailer->Subject” is used for this. By using the translation files, you can usually determine how these subjects are structured. If variables are present in the corresponding subject, you may have to use regular expressions and check the string ranges around the variable value. To keep it simple, let’s take advantage of a static value in this example.

<?php

if ( ! defined( 'ABSPATH' ) ) exit( __( 'Don\'t try to load this file directly!' ) );

add_action( 'phpmailer_init', function( $phpmailer )
{
  $phpmailer->Priority   = 3;
  $phpmailer->Mailer     = 'smtp';
  $phpmailer->From       = 'mail@your-domain.com';
  $phpmailer->FromName   = 'Your Company Name';
  $phpmailer->Sender     = $phpmailer->From;
  $phpmailer->Host       = PREFIX_MAIL_HOST;
  $phpmailer->SMTPSecure = 'ssl';
  $phpmailer->Port       = 465;
  $phpmailer->SMTPAuth   = true;
  $phpmailer->Username   = PREFIX_MAIL_USER;
  $phpmailer->Password   = PREFIX_MAIL_PSWD;
  $phpmailer->AddReplyTo('mail2@your-domain.com',$phpmailer->FromName);

  if ( false !== strpos( $phpmailer->Subject, 'Your string to check' ))
  {
    include( 'templates/email-wrap-whatever-html.php' );
    include( 'templates/email-wrap-whatever-plain.php' );
    $reason = 'This is your special reason for the emails.';
  } // end if

  else
  {
    include( 'templates/email-wrap-default-html.php' );
    include( 'templates/email-wrap-default-plain.php' );
    $reason = 'This is your default reason for the emails.';
  } // end else

  $date    = 'From '.date_i18n( get_option( 'date_format' ) ).' at '.date_i18n( get_option( 'time_format' ) );

  $search  = [ '%content%', '%reason%', '%date%' ];
  $replace = [ $phpmailer->Body, $reason, $date ];

  $message    = str_replace( $search, $replace, $emailWrapperHTML );
  $messageAlt = str_replace( $search, $replace, $emailWrapperPlain );

  $phpmailer->Body    = $message;
  $phpmailer->AltBody = $messageAlt;
}); // end add_action

Within the if-Condition, the subject line is checked for a defined content. If this content is found there, your special case templates will be added. Otherwise, your default templates are used. The different templates are only included within the respective condition, and the corresponding content is exchanged then. Depending on which WordPress plugin the data is transferred from, you can even dynamically assign the user name here. You only need to integrate the corresponding user data (ID or e-mail address) as text into the email sent via “wp_mail” and cut it out before you pass the text into the variable “$message”. This could be very interesting to make the emails more personalized for your recipients.

If you want to test how your emails look like, then you can use the following snippet.

$mailTestTo = 'mail@your-domain.com';

$mailTestSubject = 'Test-Subject';

$mailTestMessage = 'Test-Message';

$mailTestHeaders = array('Content-Type: text/html; charset=UTF-8');

wp_mail( $mailTestTo, $mailTestSubject, $mailTestMessage, $mailTestHeaders );

Final words for WP Mail

As you have seen, it is relatively easy to customize your emails without using an additional plugin. You can in an effortless way not only integrate a single template but also expand your integration into many different areas according to your requirements. Have fun and success with your new awesome and unique WordPress emails.

Have you suggestions for improvements to this article? Just use the comment area below. Do you want support for implementation or do you need help elsewhere? You can book us. For this, simply use our contact form to get in touch with us.

Get the best out of your web!

About Me

WordPress Developer Bruno Bouyajdad from Indikator Design

Bruno Bouyajdad
WordPress Developer, Photographer, video editor, 3D animator and more.

Products

Bring your Divi Blog to the next level » Indikator DesignDivi WooCommerce re-invented » Indikator Design

Follow Us

Newsletter

Pin It on Pinterest