PHP - PHPMailer - 如何将文件添加为具有正确扩展名的附件

时间:2015-07-12 01:14:00

标签: php email upload phpmailer

我正在建立一个网站并有一个表格,其中用户可以输入一些字段,即姓名,电子邮件等,但随后也可以选择上传文件。我正在使用PHPMailer构建一个电子邮件,其中包含用户数据作为电子邮件字段,然后将其发送给我,以便我可以查看它。一切正常,直到文件上传。我相对较新的PHP,所以它可能是一些小东西,但它让我疯了。在下面的代码中,我为上传的文件生成一个新名称,然后附加文件扩展名。然后我将其移至临时文件夹并尝试通过$mail->addAttachment将其附加到电子邮件中。电子邮件发送和所有内容,但附件没有扩展名 - 当我手动下载并添加适当的扩展名时,它可以工作,但由于某种原因,该文件不会作为正确的类型附加。

    // if one of the fields is set they all will be, i.e. the form has been submitted
    if (isset($_POST['firstName']))
    {
    // array to hold possible runtime errors
    $errors = array();

    // if statement to see if user failed to enter one of the required fields
    if (empty($_POST['firstName']) || empty($_POST['lastName']) || empty($_POST['email']) || empty($_POST['subject'])
    || empty($_POST['message']) || empty($_POST['phone']))
    {
    array_push($errors, 'Please enter all required fields');
    }


    // var to keep track of whether or not we have a file
    $have_file = ($_FILES['inputFile']['error'] != UPLOAD_ERR_NO_FILE);

    //checks for file upload as well
    if ($have_file)
    {
    // here a file has been uploaded, so we make sure its an acceptable type
    $ext_whitelist = array('dwg', 'asm', 'acp', '3dxml', 'cgr', 'dft', 'dxf', 'iam', 'idw', 'ipt', 'ipn', 'par', 'prt',
    'skp', 'rvt', 'rfa',' sldasm', 'slddrw', 'sldprt', 'step', 'stl');

    // var to store file array
    $file = $_FILES['inputFile'];

    // file properties stored for easier readability
    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];

    // get file extension
    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));


    if (!in_array($file_ext, $ext_whitelist))
    {
        if ($ext == 'php')
        {
            array_push($errors, 'Nice try');;
        }
        else
        {
            array_push($errors, 'Please enter a valid file type');
        }
    }


    // checks file size
    if ($file_size > 64000000)
    {
        array_push($errors, 'File too large, please call for further information');
    }
    }


    // if we have an error, we just output that, or those, otherwise, we proceed
    // with mailer
    if (!empty($errors))
    {
    foreach ($errors as $err) { ?>

        <p class="text-center" style="margin-top:20px;font-size:16px;">

            <?php echo $err; ?>

        </p>

    <?php
    }

    }
    // if here, there have been no errors
    else
    {
    require 'PHPMailer/PHPMailerAutoload.php';

    $mail = new PHPMailer;

    //mail server setup
    $mail->isSMTP();                                    // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';                     // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                             // Enable SMTP authentication
    $mail->Username = '';         // SMTP username
    $mail->Password = '';                     // SMTP password
    $mail->SMTPSecure = 'tls';                          // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                  // TCP port to connect to

    //add To and From fields
    $mail->From = '';
    $mail->FromName = 'Mailer';
    $mail->addAddress('');

    $mail->isHTML(true);                                // Set email format to HTML


    //add message contents
    $mail->Subject = $_POST['subject'];

    $mail->Body = $_POST['message'] . '<br><br>' . $_POST['firstName'] . ' ' . $_POST['lastName'] . '<br>' . $_POST['phone'];

    // adds organization if its there
    if (!empty($_POST['organization']))
    {
        $mail->Body .= '<br>' . $_POST['organization'];
    }

    // uploads/attaches file if there was one
    if($have_file)
    {
        // give file unique name and set its destination as a temporary folder
        $file_name_new = uniqid('', true) . '.' . $file_ext;
        $file_destination = sys_get_temp_dir() . '\\' . $file_name_new;

        if (move_uploaded_file($file_tmp, $file_destination))
        {
            echo $file_destination;
            $mail->addAttachment($file_destination, 'Uploaded file');
        }
        else
        {
            ?>
            <p class="text-center" style="margin-top:20px;font-size:16px;">Error sending message, please call and let us know</p>
            <?php
        }
    }

    //send the message
    if (!$mail->send())
    {
        ?>
        <p class="text-center" style="margin-top:20px;font-size:16px;">Error sending message, please call and let us know</p>
        <?php
    }
    else
    {
        ?>
        <p class="text-center" style="margin-top:20px;font-size:16px;">Message sent! Thank you for visiting us today</p>
        <?php
    }

非常感谢任何帮助。我已将某些字段留空以防止显示我的信息。即$mail->From

2 个答案:

答案 0 :(得分:2)

@Hanoncs我认为我设法得到了它。这一行:

$mail->addAttachment($file_destination, 'Uploaded file');
字面上,

在附加到'上载文件'时重命名文件。因此,显然,在电子邮件中,由于名称,文件上没有文件扩展名。因此,我所要做的就是将“上传的文件”更改为具有扩展名的内容,例如'uploadedfile.ext',它似乎工作。这是一个愚蠢但非常令人沮丧的错误,因为所有的文件上传处理似乎都运行得相当好。所以块现在看起来像这样:

    // uploads/attaches file if there was one
    if($have_file)
    {
    // give file unique name and set its destination as a temporary folder
    $file_name_new = uniqid('', true) . '.' . $file_ext;
    $file_destination = sys_get_temp_dir() . '\\' . $file_name_new;

    if (move_uploaded_file($file_tmp, $file_destination))
    {
        echo $file_destination;
        $mail->addAttachment($file_destination, 'uploadedFile.dwg');
    }
    else
    {
        ?>
        <p class="text-center" style="margin-top:20px;font-size:16px;">Error sending message, please call and let us know</p>
        <?php
    }
}

无论如何,感谢您的所有帮助,特别是有关IDE的帮助,现在就开始设置它。

答案 1 :(得分:1)

首先我要说你需要在附加时调试并检查file_ext,并确保它不是空的。

要使用文件扩展名:

$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);

让我知道你的结果,我可以进一步提供帮助。