使用PHP发送附件问题

时间:2012-10-15 09:55:25

标签: php email email-attachments

我尝试使用PHP在我的网站上发送自动创建的电子邮件。经过一番努力,我最终得到了这个脚本,但由于某种原因我得到了一个错误,我无法弄清楚原因。

function sendMail($_POST) {
    $fileatt = "http://www.mysite.com/contract.pdf";  
    $fileatt_type = "application/pdf"; 
    $fileatt_name = "contract.pdf"; 

    $email_from = "info@mysite.com"; 
    $email_subject = "Your Contract";  
    $email_message = "Thanks for your booking! Here is your contract"; 

    $email_to = $_POST['mail']; // Who the email is to

    $headers = "From: ".$email_from;

    $file = fopen($fileatt,'r'); 
    $data = fread($file,filesize($fileatt)); 
    fclose($file);

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

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

    $email_message .= "This is a multi-part message in MIME format.\n\n" . 
    "--{$mime_boundary}\n" . 
    "Content-Type:text/html; charset=\"iso-8859-1\"\n" . 
    "Content-Transfer-Encoding: 7bit\n\n" . 
    $email_message .= "\n\n";

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

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

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

    if($ok) { 
        echo "You file has been sent to the email address you specified";
    } else { 
        die("Sorry but the email could not be sent. Please go back and try again!"); 
    }
}

脚本会发送电子邮件并包含附件但附件的大小为0kb。如果我看到我的错误,这是有道理的:

Warning: filesize(): stat failed for http://www.mysite.com/test.pdf in /customers/9/7/5/mysite.com/functions.php on line 712
Warning: fread(): Length parameter must be greater than 0 in /customers/9/7/5/mysite.com/functions.php on line 712

有人可以向我提供有关如何解决此问题的更多信息吗?

3 个答案:

答案 0 :(得分:2)

这可能是由于您尝试上传的文件过大。增加服务器配置中的“Max_upload_filesize”。

答案 1 :(得分:0)

我认为最简单的解决方案是使用像PHPMailer或SwiftMailer这样的脚本。这是大多数人所做的事情,并且避免了使用PHP发送电子邮件的麻烦。尝试在PHP中使用mail()函数而不是专家是一个杀手!

答案 2 :(得分:0)

您尝试过的附件尺寸是多少?也许您应该增加上传文件大小限制,请参阅http://drupal.org/node/97193