通过PHP PEAR发送电子邮件附件

时间:2015-07-11 09:38:14

标签: php email pear mime email-attachments

我真的需要你的帮助。请在下面找到我的代码:

if (isset($_FILES['file']) and $_FILES['file'] <> '') { // Jika email disertai attachment
        $crlf = "\n";

        $headers['MIME-Version'] =  '1.0';
        $headers['Content-Type'] =  'text/html; charset="UTF-8';
        $headers['Content-Transfer-Encoding'] =  'base64\r\n';
        $headers['Date'] =  date('r', $_SERVER['REQUEST_TIME']);
        $headers['Message-ID'] =  $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'];
        $headers['From']    = "do-not-reply@sbm-itb.ac.id";
        $headers['To']      = $to;
        $headers['Subject'] = $subject;

        $mime = new Mail_mime(array('eol' => $crlf));

        $mime->setHTMLBody($body);
        foreach($_FILES['file']['tmp_name'] as $key => $value){
            $file_name = $_FILES['file']['name'][$key]; //nama file (tanpa path)
            $tmp_name  = $_FILES['file']['tmp_name'][$key]; //nama local temp file di server
            $file_type = $_FILES['file']['type'][$key]; //tipe filenya (langsung detect MIMEnya)

            $fp      = fopen($tmp_name, 'r');
            $content = fread($fp, filesize($tmp_name));
            $content = addslashes($content);
            fclose($fp);
            $data = chunk_split(base64_encode($content));

            //$mime->addAttachment($tmp_name, $file_type);
            $mime->addAttachment($data, $file_type);
        }
            $body = $mime->get();
            $headers = $mime->headers($headers);

我成功发送了我的HTML文本邮件。但是,没有我上传的附件。上面的代码出了什么问题?

谢谢。

1 个答案:

答案 0 :(得分:0)

我在这里看不到您的邮件功能?尝试这样的事情:

上传附件:

$max_allowed_file_size = 1250; // size in KB 
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "png");
$upload_folder = './uploads/'; //<-- this folder must be writeable by the script
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;

$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
//Get the uploaded file information
$name_of_uploaded_file =  basename($_FILES['uploaded_file']['name']);

//get the file extension of the file
$type_of_uploaded_file = substr($name_of_uploaded_file, 
                        strrpos($name_of_uploaded_file, '.') + 1);

$size_of_uploaded_file = $_FILES["uploaded_file"]["size"]/2048;

邮寄附件,标题等

 $message = new Mail_mime(); 
    $message->setHTMLBody($text); 
    $message->addAttachment($path_of_uploaded_file);
    $body = $message->get();
    $extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
    $headers = $message->headers($extraheaders);
    $mail = Mail::factory("mail");
    $mail->send($to, $headers, $body);