I’m facing a problem with the attachments in my php mail system.
I get all the data correctly but the attachments it’s in encoded format.
my html:
<form action="lavora-con-noi-process-form.php" method="POST" id="lavora-con-noi" enctype="multipart/form-data">
<input type="file" id="pdf-upload" name="pdf_file" accept=".pdf" style="border: none;" required>
</form>
and the php part:
<?php
$showThankYou = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$recipient_email = "[email protected]";
$name = htmlspecialchars($_POST["nome"]);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL); // Validate email format
$message = htmlspecialchars($_POST["messaggio"]);
// Check if PDF file was uploaded
if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === UPLOAD_ERR_OK) {
$file_name = $_FILES['pdf_file']['name'];
$file_tmp = $_FILES['pdf_file']['tmp_name'];
$file_type = $_FILES['pdf_file']['type'];
$file_size = $_FILES['pdf_file']['size'];
// Validate file type
if ($file_type != "application/pdf") {
echo "Errore: solo file PDF sono consentiti.";
exit;
}
// Read the uploaded file content
$file_content = file_get_contents($file_tmp);
// Create a boundary string for the multipart email
$boundary = md5(uniqid());
// Prepare the email headers
$headers = "From: [email protected]";
$headers .= "Reply-To: $emailrn";
$headers .= "Content-Type: multipart/mixed; boundary="PHP-mixed-".$boundary.""rn";
// Create the email body
$mail_body = "--PHP-mixed-" . $boundary . " rn";
$mail_body .= "Content-Type: text/plain; charset="UTF-8"rn";
$mail_body .= "Content-Transfer-Encoding: 7bitrnrn";
$mail_body .= "Nome: $namenEmail: $emailnMessaggio:n$message";
// Attach the PDF file
$mail_body .= "--PHP-mixed-" . $boundary . " rn";
$mail_body .= "Content-Type: application/pdf; name="$file_name"rn";
$mail_body .= "Content-Disposition: attachment; filename="$file_name"rn";
$mail_body .= "Content-Transfer-Encoding: base64rnrn";
$mail_body .= chunk_split(base64_encode($file_content)) . "rn";
$mail_body .= "--$boundary--rn"; // Closing boundary for the email
// Send the email
if (mail($recipient_email, "Nuovo messaggio da $name", $mail_body, $headers)) {
$showThankYou = true;
} else {
// Get the error message
$errorMessage = error_get_last()['message'];
echo "Ci sono stati problemi con l'invio dell'email: $errorMessage";
}
} else {
echo "Errore durante il caricamento del file";
}
}
?>
<?php if ($showThankYou): ?>
<p>Grazie per averci inviato un messaggio! Ti contatteremo in tempi brevi per rispondere alle tue domande.</p>
<?php endif; ?>
and this is what I get in my email:
I’ve been trying to change my php different times. Could it be something on the sever that causes the problem?
