Sending emails from the script is a very useful functionality in the web application. Most of the websites used the email sending feature to send notifications to the user. If your web application is developed with PHP or uses PHP, it’s very easy to send emails from the script using PHP.
PHP provides an easy way to send emails from the website. You can send text or HTML email with the mail() function in PHP. But sometimes email functionality needs to be extended to send an attachment with the email. Sending emails with attachments in PHP using the native mail() function requires manual handling of MIME types, encoding, and boundaries. In this tutorial, you’ll learn exactly how to send email with attachment in PHP using a working example.
In this tutorial, we will show you how to send an email with an attachment using the PHP mail() function. We will also cover how to send HTML emails with attachments (any file type, such as images, documents, and PDFs) and how to send emails to multiple recipients.
Before you can use the code in this tutorial, make sure you have the following:
To send an email with an attachment in PHP, you need to set the appropriate headers and encode the attachment file in a format that can be sent via email. The following example demonstrates how to send an email with a PDF attachment using the mail() function in PHP.
Here are the key steps involved in the process:
$to variable is the recipient’s email address, $formName is the name that will appear in the “From” field of the email, and $formEmail is the email address that will appear in the “From” field.$messageHtml variable contains the HTML content of the email. You can customize this HTML to include your desired message, formatting, and styling.$attachmentPath variable specifies the path to the file you want to attach. The script reads the file content, encodes it in base64 format, and prepares it for sending as an email attachment.<?php
// Configuration - change these values as needed
$to = 'recipient@example.com';
$formName = 'Demo Site';
$formEmail = 'sender@example.com';
// Subject of the email
$subject = 'Test email with attachment (PHP mail())';
// HTML message body
$messageHtml = <<<HTML
<html>
<head>
<title>Test Email</title>
</head>
<body>
<h1>PHP mail() with attachment</h1>
<p>This is an <strong>HTML</strong> email body.</p>
<p>Regards,<br>PHP Script</p>
</body>
</html>
HTML;
// Attachment file path (local)
$attachmentPath = __DIR__ . '/sample-attachment.pdf';
$fileSize = filesize($attachmentPath);
$handle = fopen($attachmentPath, 'rb');
$content = fread($handle, $fileSize);
fclose($handle);
$encodedContent = chunk_split(base64_encode($content));
$boundary = md5(time());
// Headers
$headers = [];
$headers[] = 'From: ' . $formName . ' <' . $formEmail . '>';
$headers[] = 'Reply-To: ' . $formEmail;
$headers[] = 'MIME-Version: 1.0';
$headers[] = "Content-Type: multipart/mixed; boundary=\"{$boundary}\"";
// Multipart body (HTML only)
$body = "--{$boundary}\r\n";
$body .= "Content-Type: text/html; charset=UTF-8\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$body .= $messageHtml . "\r\n\r\n";
// Attachment part
$body .= "--{$boundary}\r\n";
$body .= "Content-Type: application/octet-stream; name=\"".basename($attachmentPath)."\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"".basename($attachmentPath)."\"\r\n\r\n";
$body .= $encodedContent . "\r\n";
// End of mixed boundary
$body .= "--{$boundary}--";
// Send mail
$sent = mail($to, $subject, $body, implode("\r\n", $headers));
if ($sent) {
echo "Email successfully sent to {$to}\n";
} else {
echo "Failed to send email to {$to}\n";
}
?>
Send Email to Multiple Recipients:
You can send emails to multiple recipients by separating their email addresses with commas in the $to variable. For example:
$to = 'user@example.com, anotheruser@example.com';
The Cc and Bcc fields can also be added to the email headers to send copies of the email to additional recipients without revealing their email addresses to others.
$headers[] = 'Cc: cc@example.com';
$headers[] = 'Bcc: bcc@example.com';
Send Email with Multiple Attachments:
The above example demonstrates how to send an email with a single attachment. If you want to send an email with multiple attachments, you can repeat the attachment part in the email body for each file you want to attach. Each attachment should be separated by the same boundary string.
Here is a separate tutorial that explains how to send an email with multiple attachments in PHP:
mail() is not recommended for production use, especially with attachments, due to reliability and security issues.Here is a tutorial that explains how to send email via SMTP server in PHP using PHPMailer:
1. Email Not Sending on Localhost:
2. Attachment Corrupted:
3. Email Goes to Spam:
Sending emails with attachments in PHP is a common requirement for many web applications. Here we have provided the easiest way to send email with attachment in PHP. You don’t need to include any library to send HTML email with attachments. Using the PHP default mail() function you can easily send email with pdf/image attachment. This method gives you full control over email structure, but also requires careful handling of MIME formatting.
While the default mail() function can handle basic email sending, it has limitations when it comes to attachments and reliability. For production environments, it’s recommended to use dedicated libraries like PHPMailer or SwiftMailer to ensure better performance and security. If you’re building a real-world application, switching to a mailing library will save you time and prevent delivery issues.
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions
Thank you very much for great help
Great!!! Thanks a lot!!
This code worked perfect!
The code works. I get an email but my attached file (pdf or jpg) appears in hex format in email body. I’m on web host Hostinger. I think they run Linux servers. Could this have something to do with it and do I need to adjust my code. See below what I’m getting. Please help.
–==Multipart_Boundary_xe4a1d18bb25f8507066079069d78e651x
Content-Type: application/octet-stream; name=”test.pdf”
Content-Description: test.pdf
Content-Disposition: attachment;
filename=”test.pdf”; size=121846;
Content-Transfer-Encoding: base64
JVBERi0xLjQKMSAwIG9iago8PAovVHlwZSAgL1hPYmplY3QgCi9TdWJ0eXBlICAvSW1hZ2UgCi9X
aWR0aCAgNDI4IAovSGVpZ2h0ICAxNDQgCi9GaWx0ZXIgIC9GbGF0ZURlY29kZSAKL0JpdHNQZXJD
b21wb25lbnQgIDggCi9EZWNvZGVQYXJtcyA8PAovUHJlZGljdG9yICAxNSAKL0NvbG9ycyAgMyAK
…
Hello thank for the solution you save me but how can i insert php variable in htmlContent
You save my day, thanks bro !
All others solutions don’t work, even on php mail documentation.
how to add multiple Bcc address
Thanks Brohter, It Worked… None of stackoverlow.com solutions worked for me but your solution worked like a charm. Thanks again.
Nice code….but mail goes to spam. try to @gmail
Any suggestion?
Thx
friend, my file is an image, I’m sending it through a form
// Attached file
$ file = “files / codexworld.pdf”; ….. how would I receive my image here
How can I adapt to send multiple files ?, all the ones in a directory.
Thanks!!
Nice!
Nice nice! Thank you!
Thankyou so much ..helpful article..keep it up….
How to attach multiple file?
To send an email with multiple attachments, see this tutorial – https://www.codexworld.com/send-email-with-multiple-attachments-php/
I worked (unlike some other examples I had found). Thank you!
Hi, it’s working great for me!
But I have a small problem. I’ve been trying to add a Bcc in the header, and can’t seem to do it… I have no idea why. I’ve tried multiple variations of :
$headers .= “Bcc: Beny Scott”.” \n”;
Nothing works. Not with the email being hardcoded in, not with \r\n at the end, no idea why.
Use the Bcc header to add BCC mail address with this email. Add the following line of code after the first
$headers.Thanks Bro Its Works for me. You are the greatest Developer in the world
I have uploaded the sending mail script on cpanel.
Mail sent.
But very slow.
Your demo is very fast?
What’s the matter?