Search the blog
This post is very old. I no longer recommend you use this code and instead use the SwiftMailer library.

To send email attachments you need to make use of MIME (Multipurpose Internet Mail Extensions) – a mechanism that allows email to go beyond a basic, limited character set. MIME has many uses but for the purposes of this tutorial we will send a multipart/mixed MIME email; this means we can send a text email and attach a PDF file to it (for information on attaching other file types please see the end of this tutorial).

Code listing

Here’s the complete code listing.

// Settings
$name        = "Name goes here";
$email       = "someome@anadress.com";
$to          = "$name <$email>";
$from        = "John-Smith ";
$subject     = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$fileatt     = "./test.pdf";
$fileatttype = "application/pdf";
$fileattname = "newname.pdf";
$headers = "From: $from";

// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);

// This attaches the file
$semi_rand     = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers      .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"-{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage  . "\n\n";

$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";

// Send the email
if(mail($to, $subject, $message, $headers)) {

    echo "The email was sent.";

}
else {

    echo "There was an error sending the mail.";

}

You can attach any kind of file you like – you need to make sure that change the $fileatttype variable to reflect the content type of the file you are attaching (e.g. image/gif for a GIF file).

I had problems with this code when I moved the post over to WordPress. Thanks a million to Mike Cooper for pointing this out—and helping me to fix it.

The blog is no longer on WordPress so there are no issues with the quotes

To use me in a web project call me on 07843 483 078 or get a free quote now!

Tim Bennett is a freelance web designer from Leeds. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.