无法访问文件:....在电子邮件附件中发送pdf

时间:2014-08-11 14:42:30

标签: php email phpmailer

我使用php邮件程序类发送电子邮件,它工作正常。

但是现在我试图在我的电子邮件中发送附件并且我有错误。

当我点击我的按钮发送电子邮件时,我得到了我的成功消息,即电子邮件已成功发送,但我也收到此消息“无法访问文件:pdfName.pdf ”。

在我发送电子邮件的文件中,我有 php code

<?php
if(isset($_POST['sendForm'])){
    $subject = $_POST['subject'];
    $pdf = $_FILES['pdf']['name'];


    if(empty($subject) || empty($_FILES['pdf']['name'])){
        echo 'Please fill all fields';
    }
    else{
        $readSubscribers = $pdo->prepare("SELECT * FROM subscribers");  
        $readSubscribers->execute();

        if($readSubscribers->rowCount() <=0){
            echo 'We dont have any subscriber yet.';    
        }
        else{
            while($result = $readSubscribers->fetch(PDO::FETCH_ASSOC)){
            $email  = $result['email'];
            $code = md5($code);
            $msg = 'email message';  
            sendMail($subject,$msg,MAILUSER,SITENAME,$email,'',$pdf);
            }
            echo 'Email sent with sucess.';
        }
    }
}
?>

这是我的HTML

<form name="editpost" method="post" enctype="multipart/form-data"> 
    <div>
        <span>Subject:</span>
        <input type="text" name="subject" value="" />
    </div>
    <div>
        <span>Attachment:</span>
        <input type="file" name="pdf" accept="application/pdf" />                         
    </div>  
    <input type="submit" value="Send" name="sendForm"/>
</form>

此外,如果我存储我的pdf lime临时文件,如下所示:

$pdf = $_FILES['pdf']['tmp_name'];

当我点击我的按钮发送电子邮件时,我没有任何错误消息,但是当我收到电子邮件时,有这个名字:“phpF.tmp”,它无法打开......

1 个答案:

答案 0 :(得分:2)

在发送php文件中试试这个:

//first rename the uploaded file:

$filename = "/tmp/".$_FILES['pdf']['name'];
rename($_FILES['pdf']['tmp_name'], $filename);

//you can also move the uploaded file with the command:
move_uploaded_file($_FILES['pdf']['tmp_name'], $filename);

...

//and then send the changed file
sendMail($subject, $msg, MAILUSER, SITENAME, $email, '', $filename);

//and if everything is fine delete the file:
unlink($filename);

此外:

您可以检查上传的文件是否来自pdf:

if(is_uploaded_file($_FILES['pdf']['tmp_name']) && strtolower(substr($_FILES['pdf']['name'], -4)) == ".pdf")
{
    //and do something if the file is uploaded:
    if(move_uploaded_file($_FILES['pdf']['tmp_name'], $filename)
    {

    }
}

//or check the mimetype
ob_start();
$type = system("file --mime-type -b ".$filename);
ob_clean();