Прикрепить загруженный файл к электронной почте без PHPmailer

Я пытался создать контактную форму, которая позволяла бы мне загружать файлы и отправлять их по электронной почте. Я нашел большое их количество в w3schools, но я не уверен, как прикрепить его к электронному письму в нижней части кода. Я не хочу использовать PHPmailer или что-то в этом роде, потому что код почти там, просто нужно немного помочь закончить его.


PHP


<?php
$to = 'test@gmail.com';
$subject = 'Website Submission';
$company_name = $_POST['company_name'];
$ref = $_POST['ref'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}$body = <<<EMAIL

<html>

<p><h3>Email from website.</h3></p>

<p><strong>Company Name:</strong> $company_name</p>
<p><strong>Ref:</strong> $ref</p>
<p><strong>Website:</strong> $website</p>
<p><strong>Email:</strong> $email</p>
<p><strong>Tel:</strong> $tel</p>
<p><strong>Message:</strong> $message</p>

</html>

EMAIL;

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: test' . "\r\n";
$headers .= 'From: <noreply@email.co.uk>' . "\r\n";
//$headers .= 'Cc: noreply@example.com' . "\r\n";
//$headers .= 'Bcc: noreply@example.com' . "\r\n";if ($_POST['submit']){
mail($to, $subject, $body, $headers);
echo 'Message Successfully Sent.';
} else {

die('Error Email Not Sent');
}
?>

0

Решение

Вот полное переписывание, которое проверено ОК.

Sidenotes: Возможно, вам придется изменить это Content-Type: application/xml но мне не пришлось при тестировании с .jpg а также .zip файл.

У вас также есть пробелы перед вашим EMAIL; что вы не можете иметь, так как это Heredoc. Я удалил их. Это привело бы к ошибке.

<?php

$to = 'email@example.com';
$subject = 'Website Submission';
$company_name = $_POST['company_name'];
$ref = $_POST['ref'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}

$body = <<<EMAIL

<html>

<p><h3>Email from website.</h3></p>

<p><strong>Company Name:</strong> $company_name</p>
<p><strong>Ref:</strong> $ref</p>
<p><strong>Website:</strong> $website</p>
<p><strong>Email:</strong> $email</p>
<p><strong>Tel:</strong> $tel</p>
<p><strong>Message:</strong> $message</p>

</html>

EMAIL;

/* Attachment File
Attachment location */
$file_name = $target_file;

$path = $file_name;

// Read the file content

$file = $file_name;
$file_size = filesize($file_name);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));

/* Set the email header
Generate a boundary */
$boundary = md5(uniqid(time()));

// Email header
// $header = "From: ".$from_name." \r\n";

$header = 'From: <noreply@email.co.uk>' . "\r\n";
// $header .= "Reply-To: ".$reply_to."\r\n";
$header .= "MIME-Version: 1.0\r\n";

// Multipart wraps the Email Content and Attachment
$header .= "Content-Type: multipart/mixed;\r\n";
$header .= " boundary=\"".$boundary."\"";

$message .= "This is a multi-part message in MIME format.\r\n\r\n";
$message .= "--".$boundary."\r\n";

/* Email content
Content-type can be text/plain or text/html */
// $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";

// this header below is the important one if you want HTML message
$message .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "\r\n";
$message .= "$body\r\n";
$message .= "--".$boundary."\r\n";

/* Attachment
Edit content type for different file extensions */
$message .= "Content-Type: application/xml;\r\n";
$message .= " name=\"".$file_name."\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment;\r\n";
$message .= " filename=\"".$file_name."\"\r\n";
$message .= "\r\n".$content."\r\n";
$message .= "--".$boundary."--\r\n";if ($_POST['submit']){
mail($to, $subject, $message, $header);
echo 'Message Successfully Sent.';
} else {

die('Error Email Not Sent');
}
?>

Оригинальный ответ


Взят / заимствован из этот вопрос, Я смог заставить его работать некоторое время назад, когда впервые увидел вопрос:

<?php

/* Email Details */
$mail_to = "email@example.com";
$from_mail = "email_other_1@example.com";
$from_name = "Test";
$reply_to = "email_other_2@example.com";
$subject = "Test only";
// $message = "Here is your file.";

$message = "";

$message_body = "Hello this is a message.";

/* Attachment File
Attachment location */
$file_name = "attachment.zip";
$path = "files/";

// Read the file content
$file = $path.$file_name;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));

/* Set the email header
Generate a boundary */
$boundary = md5(uniqid(time()));

// Email header
// $header = "From: ".$from_name." \r\n";

$header = "From: ".$from_mail." \r\n";
$header .= "Reply-To: ".$reply_to."\r\n";
$header .= "MIME-Version: 1.0\r\n";

// Multipart wraps the Email Content and Attachment
$header .= "Content-Type: multipart/mixed;\r\n";
$header .= " boundary=\"".$boundary."\"";

$message .= "This is a multi-part message in MIME format.\r\n\r\n";
$message .= "--".$boundary."\r\n";

/* Email content
Content-type can be text/plain or text/html */
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "\r\n";
$message .= "$message_body\r\n";
$message .= "--".$boundary."\r\n";

/* Attachment
Edit content type for different file extensions */
$message .= "Content-Type: application/xml;\r\n";
$message .= " name=\"".$file_name."\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment;\r\n";
$message .= " filename=\"".$file_name."\"\r\n";
$message .= "\r\n".$content."\r\n";
$message .= "--".$boundary."--\r\n";

// Send email
if (mail($mail_to, $subject, $message, $header)) {
echo "Sent";
} else {
echo "Error";
}
?>

Итак, с вашим кодом, попробуйте изменить этот блок:

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: test' . "\r\n";
$headers .= 'From: <noreply@email.co.uk>' . "\r\n";
//$headers .= 'Cc: noreply@example.com' . "\r\n";
//$headers .= 'Bcc: noreply@example.com' . "\r\n";

с:

Sidenote: Возможно, вам придется изменить это Content-Type: application/xml но мне не пришлось при тестировании с .zip файл.

/* Attachment File
Attachment location */
$file_name = $target_file;
$path = "uploads/";

// Read the file content
$file = $path.$file_name;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));

/* Set the email header
Generate a boundary */
$boundary = md5(uniqid(time()));

// Email header
// $header = "From: ".$from_name." \r\n";

$header = 'From: <noreply@email.co.uk>' . "\r\n";
// $header .= "Reply-To: ".$reply_to."\r\n";
$header .= "MIME-Version: 1.0\r\n";

// Multipart wraps the Email Content and Attachment
$header .= "Content-Type: multipart/mixed;\r\n";
$header .= " boundary=\"".$boundary."\"";

$message .= "This is a multi-part message in MIME format.\r\n\r\n";
$message .= "--".$boundary."\r\n";

/* Email content
Content-type can be text/plain or text/html */
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "\r\n";
$message .= "$message_body\r\n";
$message .= "--".$boundary."\r\n";

/* Attachment
Edit content type for different file extensions */
$message .= "Content-Type: application/xml;\r\n";
$message .= " name=\"".$file_name."\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment;\r\n";
$message .= " filename=\"".$file_name."\"\r\n";
$message .= "\r\n".$content."\r\n";
$message .= "--".$boundary."--\r\n";

2

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector