How can PHP be used to send emails with attachments to users who submit a form?
To send emails with attachments to users who submit a form using PHP, you can use the PHP `mail()` function in combination with the `multipart/mixed` MIME type to attach files. You will need to handle file uploads from the form submission and then include the attachment in the email message.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$to = "recipient@example.com";
$subject = "Form submission with attachment";
$message = "Please see the attached file.";
$file_name = $_FILES['attachment']['name'];
$file_tmp = $_FILES['attachment']['tmp_name'];
$headers = "From: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\n";
$content = "--boundary\r\n";
$content .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$content .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$content .= $message . "\r\n";
$content .= "--boundary\r\n";
$content .= "Content-Type: application/octet-stream; name=\"" . $file_name . "\"\r\n";
$content .= "Content-Transfer-Encoding: base64\r\n";
$content .= "Content-Disposition: attachment; filename=\"" . $file_name . "\"\r\n\r\n";
$content .= chunk_split(base64_encode(file_get_contents($file_tmp))) . "\r\n";
$content .= "--boundary--";
if(mail($to, $subject, $content, $headers)){
echo "Email sent successfully with attachment.";
} else {
echo "Email sending failed.";
}
}
?>