Send Base64 Encoded Email with PHP

Base 64 is a way to representing binary data – like images – into ASCII text. You can use use Base-64 encoding to easily send binary data through HTML Mail, e-mail attachments, JSON requests and HTML forms.

The encoded data uses A-Z, a-z, 0-9 and + and /, with = as a padding character while carriage return line feed (“\r\n”) characters are inserted into the output to keep the line lengths less than 76 characters. Here is the raw source of a MIME encoded HTML Mail:

To: amit@labnol.org
Subject: This is a MIME encoded email
From: from@labnol.org
Cc: cc@labnol.org
MIME-Version: 1.0
Content-Type: multipart/alternative;boundary = "Saturday16thofAugust2014081815AM"
Message-Id: <20140816081815.6ABFB2D793B0@iMac.local>
Date: Sat, 16 Aug 2014 13:48:15 +0530 (IST)

--Saturday16thofAugust2014081815AM
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: base64

PHA+VGhlIDxiPnF1aWNrPC9iPiA8ZW0+YnJvd248L2VtPiA8dT5mb3g8L3U+IGp1bXBlZCByaWdo
dCBvdmVyIHRoZSBsYXp5IGRvZy48L3A+PGhyIC8+

You can easily send MIME encoded email messages through PHP. The base64_encode() method encodes the HTML message with base64 while chunk_split() splits the encoded messages into smaller chunks and appends “\r\n” at the end.


<?php 

$html = "<p>The <b>quick</b> <em>brown</em> <u>fox</u> jumped right over the lazy dog.</p><hr />";

$to   = "amit@labnol.org";
$cc   = "cc@labnol.org";
$bcc  = "bcc@labnol.org";
$from = "from@labnol.org";

$subject  = "This is a MIME encoded email";
$boundary = str_replace(" ", "", date('l jS \of F Y h i s A'));
$newline  = "\r\n";

$headers = "From: $from$newline".
           "Cc: $cc$newline".
           "Bcc: $bcc$newline".
           "MIME-Version: 1.0$newline".
           "Content-Type: multipart/alternative;".
           "boundary = \"$boundary\"$newline$newline".
           "--$boundary$newline".
           "Content-Type: text/html; charset=ISO-8859-1$newline".
           "Content-Transfer-Encoding: base64$newline$newline";

$headers .= rtrim(chunk_split(base64_encode($html)));

mail($to,$subject,"",$headers);

?>