Send Email With Attachments In PHP (Simple Examples)

Welcome to a tutorial on how to send email attachments in PHP. Looking to send an email with a file attachment in PHP? Well, the native PHP mail function is not the friendliest out of the box.

We have to manually format the email to send attachments with the native PHP mail() function:

  1. Define a random boundary string – $bound = "RANDOM";
  2. Set the boundary in the email header –
    • $head = "MIME-Version: 1.0" . "\r\n";
    • $head .= "Content-Type: multipart/mixed; boundary=\"$bound\"";
  3. Set the email message.
    • $body = "--$bound" . "\r\n";
    • $body .= "Content-type: text/html; charset=utf-8" . "\r\n\r\n";
    • $body .= "<p>MESSAGE<p>" . "\r\n";
  4. Manually encode and attach the file.
    • $body .= "--$bound" . "\r\n";
    • $body .= "Content-Type: application/octet-stream; name=\"ATTACH.JPG\"" . "\r\n";
    • $body .= "Content-Transfer-Encoding: base64" . "\r\n";
    • $body .= "Content-Disposition: attachment" . "\r\n\r\n";
    • $body .= chunk_split(base64_encode(file_get_contents( "ATTACH.JPG" ))) . "\r\n";
    • $body .= "--$bound--";
  5. Send the email out – mail("TO", "SUBJECT", $body, $head);

That covers the basics, but read on if you need more examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

PHP MAIL ATTACHMENT

All right, let us now get into the examples of how to send email attachments in PHP.

 

PART 1) ATTACH A SINGLE FILE

1-attach-single.php
<?php
// (A) EMAIL SETTINGS
$mailTo = "jon@doe.com";
$mailSubject = "Test Attachment";
$mailMessage = "<strong>Test Message</strong>";
$mailAttach = "attach-a.png";

// (B) GENERATE RANDOM BOUNDARY TO SEPARATE MESSAGE & ATTACHMENTS
// https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
$mailBoundary = md5(time());
$mailHead = implode("\r\n", [
  "MIME-Version: 1.0",
  "Content-Type: multipart/mixed; boundary=\"$mailBoundary\""
]);

// (C) DEFINE THE EMAIL MESSAGE
$mailBody = implode("\r\n", [
  "--$mailBoundary",
  "Content-type: text/html; charset=utf-8",
  "",
  $mailMessage
]);

// (D) MANUALLY ENCODE & ATTACH THE FILE
$mailBody .= implode("\r\n", [
  "",
  "--$mailBoundary",
  "Content-Type: application/octet-stream; name=\"". basename($mailAttach) . "\"",
  "Content-Transfer-Encoding: base64",
  "Content-Disposition: attachment",
  "",
  chunk_split(base64_encode(file_get_contents($mailAttach))),
  "--$mailBoundary--"
]);

// (E) SEND
echo mail($mailTo, $mailSubject, $mailBody, $mailHead)
  ? "OK" : "ERROR" ;

Look no further, this is pretty much just a “polished version” of the introduction snippet. We are just using implode("\r\n") to quickly build the email header/body here, instead of manually typing out "\r\n" a dozen times.

 

 

EXTRA) MANUAL FORMATTING

For you guys who want more technical information – We are formatting the email according to RFC1341 multipart.

  • As in the introduction, we have to define a BOUNDARY string and set it in the email header Content-Type: multipart/mixed; boundary="BOUNDARY".
  • For each section of the email body:
    • Start with --BOUNDARY.
    • Followed by the Content-type headings.
    • An empty line break, then the content itself.
  • Lastly, the email must be closed with --BOUNDARY--.

That’s all. So if you want to add more attachments, it is only a manner of adding more --BOUNDARY segments.

 

PART 2) ATTACH MULTIPLE FILES

2-attach-many.php
<?php
// (A) EMAIL SETTINGS
$mailTo = "jon@doe.com";
$mailSubject = "Test Attachment";
$mailMessage = "<strong>Test Message</strong>";
$mailAttach = ["attach-a.png", "attach-b.png"];

// (B) GENERATE RANDOM BOUNDARY TO SEPARATE MESSAGE & ATTACHMENTS
// https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
$mailBoundary = md5(time());
$mailHead = implode("\r\n", [
  "MIME-Version: 1.0",
  "Content-Type: multipart/mixed; boundary=\"$mailBoundary\""
]);

// (C) DEFINE THE EMAIL MESSAGE
$mailBody = implode("\r\n", [
  "--$mailBoundary",
  "Content-type: text/html; charset=utf-8",
  "",
  $mailMessage
]);

// (D) MANUALLY ENCODE & ATTACH THE FILES
foreach ($mailAttach as $attach) {
  $mailBody .= implode("\r\n", [
    "",
    "--$mailBoundary",
    "Content-Type: application/octet-stream; name=\"". basename($attach) . "\"",
    "Content-Transfer-Encoding: base64",
    "Content-Disposition: attachment",
    "",
    chunk_split(base64_encode(file_get_contents($attach))),
    "--$mailBoundary"
  ]);
}
$mailBody .= "--";

// (E) SEND
echo mail($mailTo, $mailSubject, $mailBody, $mailHead)
  ? "OK" : "ERROR" ;

Want to attach many files? Yes, it’s as simple as that – Loop through all the files, add as many --BOUNDARY sections as required.

 

 

PART 3) PHPMAILER LIBRARY

3-php-mailer.php
<?php
// (A) LOAD PHPMAILER
// https://github.com/PHPMailer/PHPMailer
// composer require phpmailer/phpmailer
require "vendor/autoload.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);

// (B) SET EMAIL
$mail->From = "you@site.com";
$mail->addAddress("jon@doe.com");
$mail->isHTML(true);
$mail->Subject = "Test Attachment";
$mail->Body = "<strong>Test Message</strong>";
$mail->addAttachment("attach-a.png");
$mail->addAttachment("attach-b.png");

// (C) SEND MAIL
try {
  $mail->send();
  echo "OK";
} catch (Exception $ex) { echo $mail->ErrorInfo; }

Lastly, if the manual formatting is too much of a hassle, try out the PHPMailer library. This is a popular alternative, and it should not be difficult to see why… The above example should be self-explanatory.

 

 

EXTRAS

That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

4 thoughts on “Send Email With Attachments In PHP (Simple Examples)”

Leave a Comment

Your email address will not be published. Required fields are marked *