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

0

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


PHP


<?php  
    $to = '[email protected]';
    $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: <[email protected]>' . "\r\n";
    //$headers .= 'Cc: [email protected]' . "\r\n";
    //$headers .= 'Bcc: [email protected]' . "\r\n";


    if ($_POST['submit']){
    mail($to, $subject, $body, $headers);
    echo 'Message Successfully Sent.';
    } else {

        die('Error Email Not Sent');
    } 
    ?>
  • 0
    Немного погуглив, вы получите решение, подобное этому: webcheatsheet.com/php/send_email_text_html_attachment.php Но я предлагаю вам использовать PHPMailer или другую библиотеку, чтобы облегчить вашу жизнь.
  • 0
    @lolka_bolka Hm, я не совсем уверен, но я думаю , что я попробовал это один сам раньше , и это не работает для меня. Я должен был найти что-то еще. Я должен был бы повторно проверить это, чтобы быть уверенным на 100%.
Показать ещё 8 комментариев
Теги:
file-upload
contact-form

1 ответ

2
Лучший ответ

Здесь полный переписать, который протестировал ОК.

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

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

<?php  

    $to = '[email protected]';
    $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: <[email protected]>' . "\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 protected]";
$from_mail = "[email protected]";
$from_name = "Test";
$reply_to = "[email protected]";
$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: <[email protected]>' . "\r\n";
//$headers .= 'Cc: [email protected]' . "\r\n";
//$headers .= 'Bcc: [email protected]' . "\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: <[email protected]>' . "\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";

  • 0
    Спасибо, я попробую завтра, когда у меня будет больше времени и сообщу.
  • 0
    @ jonathan5660 Пожалуйста. Однако при тестировании обнаружил ошибку. Я буду вносить изменения в ближайшее время.
Показать ещё 11 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню