2 php tutorials

Two PHP tutorials: How To Send HTML Mail With PHP, How To Send Mail with Attachment in PHP (computing; computer language)

How To Send Mail with Attachment in PHP

Xah Lee, 2009-01-14

This page shows you how to send email with attached file, using PHP.

Sending email in php is extremely easy. All you have to do is call the “mail” function. But how do you send out email with attachment?

There are php packages that allows you to do that, however, they will often need installation of the package, and if you are using a web hosting service provider, sometimes that is not possible. Luckily, it is not difficult to write a simple code that does it. All you have to do is to encode your mail payload as multipart MIME↗.

Here's a simple working example of sending html mail with attached file:


$fromAddr = 'staff@example.com'; // the address to show in From field.
$recipientAddr = 'jane@example.org';
$subjectStr = 'Thank you';

$mailBodyText = <<<END89283
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Thank You</title>
<b>Login:</b> {$_POST['login']}<br>
<b>Password:</b> {$_POST['password']}<br>

$filePath = 'uploaded_files/great_house.jpg';
$fileName = basename($filePath);
$fileType = 'image/jpeg';
/* to find out what string to use for type, see
or $_FILES['attachment']['type'];

/* encode the email content */


From: $fromAddr
MIME-Version: 1.0
Content-Type: multipart/mixed;

// Add a multipart boundary above the plain message 
$mailBodyEncodedText = <<<TTTTTTTTTTTTTTTTT
This is a multi-part message in MIME format.

Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable



$file = fopen($filePath,'rb'); 
$data = fread($file,filesize($filePath)); 
$data = chunk_split(base64_encode($data));

// file attachment part
$mailBodyEncodedText .= <<<FFFFFFFFFFFFFFFFFFFFF
Content-Type: $fileType;
Content-Disposition: attachment;
Content-Transfer-Encoding: base64




if (
mail( $recipientAddr , $subjectStr , $mailBodyEncodedText, $headers )
) {
  echo '<p>Send successfully!</p>';
} else {
  echo '<p>Bah!</p>';


Popular posts from this blog

11 Years of Writing About Emacs

does md5 creates more randomness?

Google Code shutting down, future of ErgoEmacs