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);

?>

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫢🏻