附件不会与phpmailer一起发送

时间:2014-03-02 16:37:09

标签: php phpmailer file-io

我正在尝试使用phpMailer脚本发送附件。

由于我的电子邮件发送正确,所以一切正常,但是我确实遇到了未发送的附件的问题。

HTML部分:

<p>
   <label>Attachment :</label>
   <input name="doc" type="file">
</p>

PHP:

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();               
$mail->Host = '*****';  
$mail->SMTPAuth = true; 
$mail->Port = 465;
$mail->Username = '*****';  
$mail->Password = '*****'; 
$mail->SMTPSecure = 'ssl'; 

$mail->From = $_POST["name"];
$mail->FromName  = 'Your Name';
$mail->Subject   = 'Message Subject';
$mail->addAddress('*****');    

$mail->addAttachment($_FILES["doc"]); 
$mail->isHTML(true);   

$mail->Subject = 'Here is the subject';
$mail->Body    = "You got a new message from your website :

    Name:  $_POST[name]
    Company:  $_POST[company]
    Phone:  $_POST[phone]
    Email:  $_POST[email]
    Message:  $_POST[message]";

if(!$mail->send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
   exit;
}

?>

<!DOCTYPE HTML>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<p> <img src="img/correct.png" alt="icon" style=" margin-right: 10px;">Thank you! We will get back to you soon.</p>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

Try:

    if (isset($_FILES['doc']) &&
        $_FILES['doc']['error'] == UPLOAD_ERR_OK) {
        $mail->AddAttachment($_FILES['doc']['tmp_name'],
                             $_FILES['doc']['name']);
    }

Basic example can also be found [here](https://code.google.com/a/apache-extras.org/p/phpmailer/wiki/AdvancedMail).

The function definition for `AddAttachment` is:

    public function AddAttachment($path,
                                  $name = '',
                                  $encoding = 'base64',
                                  $type = 'application/octet-stream')

答案 1 :(得分:0)

请查看PHP file uploads的工作原理。这个数组键:

$_FILES["doc"]

...永远不会包含文件。最多,它将包含一个数组,其中包含有关在何处查找文件的信息。

答案 2 :(得分:0)

未经测试的解决方案,但应该有效:

变化

$mail->addAttachment($_FILES["doc"]); 

$mail->addAttachment($_FILES["doc"]["tmp_name"], $_FILES["doc"]["name"], "base64", $_FILES["doc"]["tmp_type"]);

但是,请考虑learning php upload file handling已被其他人评论过。 未经验证,请勿使用用户输入。决不!