尝试使用PHP邮件发送附件()

时间:2018-02-15 16:05:43

标签: php email

我尝试将上传的文件从表单存储到uploads文件夹,并将该文件作为附件发送到电子邮件。电子邮件发送完全正常,还有附件,但附件不可读/已损坏。

我尝试过多种文件类型并没有区别,我仍然有同样的错误。

    <?php

//Store File
if (!empty($_FILES) && isset($_FILES['upload'])) {
    switch ($_FILES['upload']["error"]) {
        case UPLOAD_ERR_OK:
            $target = "uploads/";
            $target = $target . basename($_FILES['upload']['name']);

            if (move_uploaded_file($_FILES['upload']['tmp_name'], $target)) {
                $status        = "The file " . basename($_FILES['upload']['name']) . " has been uploaded";
                $imageFileType = pathinfo($target, PATHINFO_EXTENSION);
            } else {
                $status = "Sorry, there was a problem uploading your file.";
            }
            break;

    }

    echo "Status: {$status}<br/>\r\n";

}


$fileatt      = getcwd() . "/uploads"; // Path to the file
$fileatt_type = "application/pdf"; // File Type
$fileatt_name = $_FILES['upload']['name']; // Filename that will be used for the file as the attachment

$email_from    = $_POST['email']; // Who the email is from
$email_subject = "Your attached file"; // The Subject of the email
$email_message = "Thanks for visiting mysite.com! Here is your free file.";
$email_message .= "Thanks for visiting."; // Message that the email has in it

$email_to = 'test@test.com'; // Who the email is to

$headers = "From: " . $email_from;

$file = fopen($fileatt . "/" . $fileatt_name, 'rb');
$data = fread($file, filesize($fileatt . "/" . $fileatt_name));
fclose($file);

$semi_rand     = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\r\nMIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\"";

$email_message .= "This is a multi-part message in MIME format.\r\n\r\n" . "--{$mime_boundary}\r\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\r\n" . "Content-Transfer-Encoding: 7bit\r\n\r\n" . $email_message .= $_POST['email'] . "<br>" . $_POST['firstname'] . "<br>" . $_POST['surname'] . "<br>" . $_POST['degree'] . "<br>" . "\r\n\r\n";

$data = chunk_split(base64_encode($data));

$email_message .= "--{$mime_boundary}\r\n" . "Content-Type: {$fileatt_type};\r\n" . " name=\"{$fileatt_name}\"\r\n" . "Content-Disposition: attachment;\r\n" . " filename=\"{$fileatt_name}\"\r\n" . "Content-Transfer-Encoding: base64\r\n\r\n" . $data .= "\r\n\r\n" . "--{$mime_boundary}--\r\n";

$ok = mail($email_to, $email_subject, $email_message, $headers);

if ($ok) {
    echo "You file has been sent
    to the email address you specified.

    Make sure to check your junk mail!

    Click here to return to mysite.com.";

} else {
    die("Sorry but the email could not be sent. Please go back and try again!");
}


?>

请有人指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

您可以在此处找到解决方案。

完全解释需要再次提供相同的信息。

Solution

相关问题