Attaching PDFs to Emails in PHP: Beyond the Basic mail() Function
Your current implementation using the native mail() function is functional for sending plain text, but it lacks the headers required to handle MIME multipart messages. To attach a PDF, you must explicitly tell the mail server that the email contains multiple parts: a text header and an encoded attachment. Without these specific headers, the file data will either be ignored or displayed as raw binary characters in your inbox.
The core issue lies in how SMTP handles attachments. A simple mail() call treats the body string as plain ASCII. To attach a file, you need to construct a multipart/mixed message where each part is separated by a boundary string. This boundary ensures the email client knows exactly where the text ends and where the binary PDF data begins.
Here is how you can modify your existing code to include an attachment:
$to = "me@myemail.com";
$subject = "My message subject";
$message = "Hello,\n\nThis is sending a text only email, but I would like to add a PDF attachment if possible.";
$from = "Jane Doe <janedoe@myemail.com>";
// Define the file path and read its binary content
$file_path = "/path/to/your/document.pdf";
$file_content = file_get_contents($file_path);
// Get the filename from the path for the Content-Disposition header
$file_name = basename($file_path);
// Generate a unique boundary string (must be quoted if it contains special characters)
$boundary = md5(uniqid(rand(), true));
// Construct the headers
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
// Part 1: The plain text body
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$body .= $message . "\r\n";
// Part 2: The PDF attachment
$body .= "--$boundary\r\n";
$body .= "Content-Type: application/pdf; name=\"$file_name\"\r\n";
$body .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
// Read the binary file and encode it for transmission via email
$encoded_content = chunk_split(base64_encode($file_content));
$body .= $encoded_content . "\r\n";
// Close the multipart message
$body .= "--$boundary--\r\n";
mail($to, $subject, $body, $headers);
echo "Mail Sent!";
In this implementation, we first read the PDF file into memory using file_get_contents(). Since email protocols transmit data as text streams, binary files must be encoded. We use Base64 encoding to convert the binary PDF data into a safe ASCII string that can travel through standard SMTP servers without corruption. The chunk_split() function adds line breaks every 76 characters, which is the standard length for Base64 lines to ensure compatibility with older email clients.
You must also handle the Content-Disposition header carefully. The filename specified here determines what the recipient sees in their download dialog. If you are sending files from a server where paths might differ between environments, it is safer to extract just the filename rather than relying on the full path.
One significant trade-off with this approach is memory usage. Loading a large PDF directly into memory with file_get_contents() can be problematic if the file exceeds available RAM or if you are sending many emails simultaneously in a loop. For larger files, consider using stream_copy_to_stream to write the attachment to a temporary file and stream it directly to the message body, which is more memory-efficient.
Another potential pitfall involves the Content-Transfer-Encoding. While Base64 is standard, some older systems might prefer Quoted-Printable for text parts. However, for binary attachments like PDFs, Base64 remains the safest choice to prevent any character set translation issues that could corrupt the document structure.
If you are building a larger application stack, native PHP mail() functions often lack robustness compared to modern frameworks. In Laravel, for instance, the Mail facade handles MIME encoding and attachments automatically, reducing the risk of header formatting errors. You might find useful patterns for handling these scenarios at https://laravelcompany.com, particularly if you are evaluating migration paths from procedural PHP to a structured framework environment.