If you haven’t already tried it, the PHPMailer class is an excellent way of sending email using PHP. It makes all those dreaded email tasks (multiple message parts, encoding, attachments etc.) really nice and easy.

Today however I came across a problem sending HTML formatted email – only occuring when sending via the PHP mail() transport rather than SMTP.

I eventually traced it to a large block of HTML which formed part of the formatted email. This was generated by a WYSIWYG editor and had no newline characters, and so was too long to handle for the mail() function (the SMTP transport was able to resolve the issue, but I didn’t want to use SMTP for this application).

The $mail->WordWrap parameter didn’t seem to help either.

So I rustled up a quick little function to split the HTML at opening tag boundaries, which solved the problem while keeping the code tidy – here it is:

/**
* Function to wrap HTML, but only at opening tag boundaries
* @param    $s            the HTML string to wrap
* @param    $chars  the number of chararacters to allow per line
* @return $s            the modified HTML
*/
function htmlWrap($s, $chars = 40) {
$aChunks = explode('<', $s);

$sLine     = '';
$aLines  = array();

foreach($aChunks as $i => $sChunk) {
$sLine .= ($i == 0 ? '' : '<') . $sChunk;

// Check if line length too long
if(strlen($sLine) + strlen(@$aChunks[$i+1]) + 1 >= $chars) {
$aLines[]    =    $sLine;
$sLine        = '';
}
}

return implode("\n", $aLines);
}

You can use this as so:

$Mail             = new PHPMailer();
$Mail->MsgHTML(htmlWrap('Your HTML email message here...'));
...