3 Ways To Send Email 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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Mail Attachment Useful Bits & Links
The End

 

DOWNLOAD & NOTES

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

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

PHP MAIL ATTACHMENT

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

 

PART 1) ATTACH SINGLE FILE

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

// (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 = "john@doe.com";
$mailSubject = "Test Attachment";
$mailMessage = "<strong>Test Message</strong>";
$mailAttach = ["capybara.jpg", "owl.jpg"];

// (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("john@doe.com");
$mail->isHTML(true);
$mail->Subject = "Test Attachment";
$mail->Body = "<strong>Test Message</strong>";
$mail->addAttachment("capybara.jpg");
$mail->addAttachment("owl.jpg");

// (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.

 

 

USEFUL BITS & LINKS

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

 

INFOGRAPHIC CHEAT SHEET

Send Attachment With PHP Mail (click to enlarge)

 

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!

Leave a Comment

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