You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP带附件表单邮件发送异常:PDF附件未发送且输出乱码

Fixing PHP Email Attachment Issues (PDF Not Sending + Garbled Output)

Hey, I see exactly what's causing your PDF attachment to fail and the garbled text showing up. Let's walk through the fixes and get your email working properly:

Key Issues in Your Code

  • Incomplete MIME Multipart Structure: You added the attachment to the header but didn't wrap your main message body in its own MIME section. This makes email clients misinterpret the attachment content as part of the message, leading to garbled text.
  • Undefined $header Variable: You start appending to $header with $header .= ... without initializing it first. This can trigger warnings and break your email headers.
  • Unreliable File Extension Check: Using substr to grab the last 4 characters is error-prone (e.g., files like my.document.pdf would fail this check). We'll use pathinfo for a more accurate extension lookup.
  • Missing Final Boundary Closure: You need to close the multipart boundary at the end of your headers to signal the end of all email parts.

Optimized Working Code

<?php 
$message_sent = false;
$invalid_class_name = ""; // Initialize error class variable

if(isset($_POST) && !empty($_POST)){
    if(!empty($_FILES['attachment']['name'])){
        $file_name = $_FILES['attachment']['name']; 
        $temp_name = $_FILES['attachment']['tmp_name']; 
        $file_type = $_FILES['attachment']['type']; 

        // Fix: Use pathinfo for reliable extension extraction
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed_extensions = array("doc", "docx", "pdf", "zip", "png"); 

        if(in_array($file_ext, $allowed_extensions)) { 
            if(isset($_POST['email']) && !empty($_POST['email'])) { 
                if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
                    $ClientName = $_POST['name']; 
                    $ClientEmail = $_POST['email']; 
                    $ClientSubject = $_POST['subject']; 
                    $ClientWords = $_POST['words']; 
                    $ClientTime = $_POST['time']; 
                    $ClientTranslation = $_POST['translation']; 
                    $ClientMessage = $_POST['message']; 

                    $to = "(your email address)"; 
                    $uid = md5(uniqid(time())); // Unique boundary identifier

                    // Fix: Initialize $header properly
                    $header = "From: " . $ClientName . " <" . $ClientEmail . ">\r\n";
                    $header .= "Reply-To: " . $ClientEmail . "\r\n";
                    $header .= "MIME-Version: 1.0\r\n";
                    $header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
                    $header .= "This is a multi-part message in MIME format.\r\n\r\n";

                    // 1. Add the plain text message body section
                    $header .= "--" . $uid . "\r\n";
                    $header .= "Content-Type: text/plain; charset=utf-8\r\n";
                    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
                    $header .= "From: " . $ClientName . "\r\n";
                    $header .= "Email: " . $ClientEmail . "\r\n";
                    $header .= "Subject: " . $ClientSubject . "\r\n";
                    $header .= "Words: " . $ClientWords . "\r\n";
                    $header .= "Time: " . $ClientTime . "\r\n";
                    $header .= "Translation Use: " . $ClientTranslation . "\r\n";
                    $header .= "Message: " . $ClientMessage . "\r\n\r\n";

                    // 2. Add the attachment section
                    $file_content = chunk_split(base64_encode(file_get_contents($temp_name)));
                    $header .= "--" . $uid . "\r\n";
                    $header .= "Content-Type: " . $file_type . "; name=\"" . $file_name . "\"\r\n";
                    $header .= "Content-Transfer-Encoding: base64\r\n";
                    $header .= "Content-Disposition: attachment; filename=\"" . $file_name . "\"\r\n\r\n";
                    $header .= $file_content . "\r\n\r\n";

                    // Fix: Close the multipart boundary
                    $header .= "--" . $uid . "--\r\n";

                    // Send the email (note: third parameter is empty string since body is in headers)
                    if(mail($to, $ClientSubject, "", $header)){
                        $message_sent = true;
                    } else {
                        // Optional: Add error handling if mail fails
                        $invalid_class_name = "form-invalid";
                    }
                } else{
                    $invalid_class_name = "form-invalid"; 
                } 
            } 
        } else {
            // Optional: Handle invalid file extension error
            $invalid_class_name = "form-invalid";
        }
    } else {
        // Optional: Handle no file uploaded error if needed
        $invalid_class_name = "form-invalid";
    }
} 
?>

Additional Notes

  • Email Body Placement: Notice we moved the entire message body into the $header (as a MIME text section) instead of using the $body parameter in mail(). This is required for multipart emails to be parsed correctly.
  • Charset Support: Added charset=utf-8 to ensure special characters in your message display correctly.
  • Error Handling: Added basic error handling for invalid files, invalid emails, and failed mail sends (you can expand this with user-friendly messages).
  • Testing: Always test with different email clients (Gmail, Outlook, etc.) to ensure attachments render correctly.

内容的提问来源于stack exchange,提问作者AtiqRoh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:52:42