Welcome to our comprehensive guide on PHP Email Attachments! In this lesson, we'll learn how to send emails with attachments using PHP, making your emails more informative and practical. Let's dive in!
Before we start, let's quickly cover the basics:
Attaching files to emails can be useful in various scenarios:
To send emails with attachments in PHP, we'll use the built-in mail() function. However, it doesn't support attachments directly, so we'll use the mail() function with a helper function called mail_attachments().
The mail() function is used to send emails in PHP. Here's the basic syntax:
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )$to: The recipient's email address.$subject: The email's subject.$message: The email's content.$additional_headers: Additional headers for the email (optional).$additional_parameters: Additional parameters for the email (optional).The mail_attachments() function helps us to send attachments with the email. Here's the basic syntax:
array mail_attachments ( string $filename , string $mime_type , string $encoding , string $disposition )$filename: The name of the file to be attached.$mime_type: The MIME type of the file (e.g., text/plain, image/jpeg).$encoding: The encoding of the file (e.g., base64, binary).$disposition: The disposition of the attachment (e.g., attachment, inline).Let's create a complete example:
<?php
// Attachment details
$file = 'example.pdf';
$mime = 'application/pdf';
// Email details
$to = 'recipient@example.com';
$subject = 'Here is your attachment';
$message = 'Please find the attached file.';
$headers = "From: Sender Name <sender@example.com>\r\n";
$headers .= "Reply-To: Sender Name <sender@example.com>\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=PHP-mixed-boundary-" . uniqid() . "\r\n";
// Attach the file
ob_start();
echo "This is a multi-part message in MIME format\n";
echo "--PHP-mixed-boundary-" . uniqid() . "\n";
echo "Content-Type: text/plain; charset=UTF-8\n";
echo "Content-Transfer-Encoding: 7bit\n\n";
echo $message . "\n\n";
$attachment = mail_attachments($file, $mime, 'base64', 'attachment');
foreach ($attachment as $header) {
echo $header;
}
echo "--PHP-mixed-boundary-" . uniqid() . "--\n";
ob_end_clean();
// Send the email
mail($to, $subject, ob_get_clean(), $headers);
?>In this example, we're sending a PDF file named example.pdf to the recipient's email. Make sure you have the file in your project directory.
What is the built-in function in PHP used to send emails?
That's it for our PHP Email Attachments tutorial! We hope this lesson has helped you understand how to send emails with attachments using PHP. Happy coding! π