Extra blank lines when sending HTML-friendly emails in PHP with Amazon SES

I’m using Amazons SES to send emails, but I wanted to send an HTML-friendly one (with a design, some colors, etc.). I knew that all styles had to be inline, but I running into an error: there were extra lines (carriage returns) when the email was sent out.

I had two variables that defined the HTML header and footer . This was part of the template:

$TEMPLATE_TOP = '<body>
<table width="600" align="center" cellspacing="0" cellpadding="0" border="0">
<tr>
<td> ;

and

$TEMPLATE_BOTTOM = '
</td>
</tr>
</table>';

Of course, for readability, I indent and put the tags on new lines — and this is what was causing the incorrect formatting (extra blank lines).

The solution is to replace chr(10) and chr(13) with a blank. So after you make the template pieces, add this in after :

$TEMPLATE_TOP = str_replace(chr(10), "", $TEMPLATE_TOP);
$TEMPLATE_TOP = str_replace(chr(13), "", $TEMPLATE_TOP);
$TEMPLATE_BOTTOM = str_replace(chr(10), "", $TEMPLATE_BOTTOM);
$TEMPLATE_BOTTOM = str_replace(chr(13), "", $TEMPLATE_BOTTOM);

I was sending an email from (multiple) functions. To make it accessible, I put those (2) in separate constants:

define("TEMPLATE_TOP", $TEMPLATE_TOP);
define("TEMPLATE_BOTTOM", $TEMPLATE_BOTTOM);

So the body of the email (in each function) becomes:

constant('TEMPLATE_TOP') . $email_body . constant('TEMPLATE_BOTTOM');

(of course, where $email_body has your content).

By the way: if you thought this blog post was helpful, check out the book I wrote on PHP, geared toward intermediate web developers.

Originally published at stevesohcot.com on April 3, 2017.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store