使用phpMailer和PHP从表单发送文件附件

使用phpMailer和PHP从表单发送文件附件,php,file-upload,phpmailer,email-attachments,Php,File Upload,Phpmailer,Email Attachments,我在example.com/contact us.php上有一个表单,看起来像这样(简化): 电子邮件正确发送正文,但没有上传的\u文件附件 我的问题 我需要将表格中的文件上传到电子邮件,然后发送。我不在乎在process.php脚本通过电子邮件发送文件后保存该文件 我知道我需要添加AddAttachment()某个地方(我假设在正文行下)用于发送附件。但是 我应该在process.php文件的顶部放些什么来拉入文件上传的\u文件?像是使用$\u FILES['uploaded\u file']

我在
example.com/contact us.php
上有一个表单,看起来像这样(简化):

电子邮件正确发送正文,但没有
上传的\u文件附件

我的问题

我需要将表格中的文件
上传到电子邮件,然后发送。我不在乎在
process.php
脚本通过电子邮件发送文件后保存该文件

我知道我需要添加
AddAttachment()
某个地方(我假设在
正文
行下)用于发送附件。但是

  • 我应该在
    process.php
    文件的顶部放些什么来拉入文件
    上传的\u文件
    ?像是使用
    $\u FILES['uploaded\u file']
    从contact-us.php页面拉入文件吗
  • AddAttachment()的内部内容
    用于附加文件并与电子邮件一起发送,此代码需要放在哪里
  • 请帮助并提供代码!谢谢

    试试看:

    if (isset($_FILES['uploaded_file']) &&
        $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
        $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                             $_FILES['uploaded_file']['name']);
    }
    
    还可以找到基本示例

    AddAttachment
    的函数定义为:

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

    您将使用
    $\u FILES['uploaded\u file']['tmp\u name']
    ,这是PHP存储上传文件的路径(它是一个临时文件,在脚本结束时由PHP自动删除,除非您将其移到/复制到其他地方)

    假设您的客户端表单和服务器端上传设置是正确的,则无需执行任何操作即可“拉入”上传。它将神奇地出现在tmp_名称路径中

    请注意,您必须验证上载是否确实成功,例如:

    if ($_FILES['uploaded_file']['error'] === UPLOAD_ERR_OK) {
        ... attach file to email ...
    }
    
    否则,您可能会尝试使用损坏/部分/不存在的文件进行附件。

    无法从客户端PC附加文件(上载) 在HTML表单中,我没有添加以下行,因此没有附件:

    enctype=“多部分/表单数据”

    在表格中添加了上面的行(如下所示)之后,附件就完美了

    <form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">
    

    此代码帮助我发送附件

    $mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
    

    将AddAttachment(…)代码替换为上述代码

    使用此代码在phpmailer中使用html表单发送带有上载文件选项的附件

     <form method="post" action="" enctype="multipart/form-data">
    
    
                        <input type="text" name="name" placeholder="Your Name *">
                        <input type="email" name="email" placeholder="Email *">
                        <textarea name="msg" placeholder="Your Message"></textarea>
    
    
                        <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
                        <input type="file" name="userfile"  />
    
    
                    <input name="contact" type="submit" value="Submit Enquiry" />
       </form>
    
    
        <?php
    
    
    
    
            if(isset($_POST["contact"]))
            {
    
                /////File Upload
    
                // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
                // of $_FILES.
    
                $uploaddir = 'uploads/';
                $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
    
                echo '<pre>';
                if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                    echo "File is valid, and was successfully uploaded.\n";
                } else {
                    echo "Possible invalid file upload !\n";
                }
    
                echo 'Here is some more debugging info:';
                print_r($_FILES);
    
                print "</pre>";
    
    
                ////// Email
    
    
                require_once("class.phpmailer.php");
                require_once("class.smtp.php");
    
    
    
                $mail_body = array($_POST['name'], $_POST['email'] , $_POST['msg']);
                $new_body = "Name: " . $mail_body[0] . ", Email " . $mail_body[1] . " Description: " . $mail_body[2];
    
    
    
                $d=strtotime("today"); 
    
                $subj = 'New enquiry '. date("Y-m-d h:i:sa", $d);
    
                $mail = new PHPMailer(); // create a new object
    
    
                //$mail->IsSMTP(); // enable SMTP
                $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only ,false = Disable 
                $mail->Host = "mail.yourhost.com";
                $mail->Port = '465';
                $mail->SMTPAuth = true; // enable 
                $mail->SMTPSecure = true;
                $mail->IsHTML(true);
                $mail->Username = "admin@domain.net"; //from@domainname.com
                $mail->Password = "password";
                $mail->SetFrom("admin@domain.net", "Your Website Name");
                $mail->Subject = $subj;
                $mail->Body    = $new_body;
    
                $mail->AddAttachment($uploadfile);
    
                $mail->AltBody = 'Upload';
                $mail->AddAddress("recipient@domain.com");
                 if(!$mail->Send())
                    {
                    echo "Mailer Error: " . $mail->ErrorInfo;
                    }
                    else
                    {
    
                    echo '<p>       Success              </p> ';
    
                    }
    
            }
    
    
    
    ?>
    
    
    

    请参考。

    嘿,伙计们,下面的代码对我来说非常好。只需将setFrom和addAddress替换为您的首选项即可

    <form id='form'>
    <input type='file' name='file' />
    <input type='submit' />
    </form>
    

    在我自己的例子中,我在表单上使用了
    serialize()
    ,因此文件没有被发送到php。如果您使用的是jquery,请使用
    FormData()
    。比如说

    $('#form').submit(function (e) {
    e.preventDefault();
    var formData = new FormData(this); // grab all form contents including files
    //you can then use formData and pass to ajax
    
    });
    

    这将非常有效

    
    
    我实现了您的代码(第一个框),与您的代码完全相同,但它仍然没有将其附加到电子邮件中。如果我使用的是
    ob_start()
    然后
    $body=ob_get_contents()这会有任何负面影响吗?还有,有没有办法确保文件是从表单附加的?我不认为这会有负面影响。我的代码检查一个文件是否真的上传了,并且上传没有错误,所以可能有问题。如果
    var\u dump($\u文件),您会看到什么;退出?我是个白痴-我的表单中有正确的操作,但是JS验证链接到了另一个表单操作(没有文件上传也一样)。非常感谢你!!还有一个问题,我如何将文件类型限制为仅限于图像、pdf、Word、Excel和CAD文件?您可以检查上载文件名的扩展名,但这并不可信。文件的mime类型也已发送,但这也是不可信的。如果您有PHP5.3或更高版本,您可以使用来尝试检测文件的mime类型,该类型将根据文件内容识别pdf、Word、excel或各种图像类型。在PHP5.3之前,您可以为它安装Pecl扩展。还有一个问题。。。如何允许上载
    .dwg
    文件?我不能因为这个而对mime类型下罚款?(AutoCad)我尝试了
    application/acad
    ,但它不起作用。您能提供我在
    AddAttachment()中实际放置的内容吗部分?以您的代码为基础,它没有此处建议的答案的安全问题。我今天得出的有用提示:在发送电子邮件之前,不要
    取消服务器上附件文件的链接。
    
    <?php
    /**
     * PHPMailer simple file upload and send example.
     */
    //Import the PHPMailer class into the global namespace
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    $msg = '';
    if (array_key_exists('userfile', $_FILES)) {
        // First handle the upload
        // Don't trust provided filename - same goes for MIME types
        // See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
        $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name']));
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) 
        {
            // Upload handled successfully
            // Now create a message
    
            require 'vendor/autoload.php';
            $mail = new PHPMailer;
            $mail->setFrom('info@example.com', 'CV from Web site');
            $mail->addAddress('blabla@gmail.com', 'CV');
            $mail->Subject = 'PHPMailer file sender';
            $mail->Body = 'My message body';
    
            $filename = $_FILES["userfile"]["name"]; // add this line of code to auto pick the file name
            //$mail->addAttachment($uploadfile, 'My uploaded file'); use the one below instead
    
            $mail->addAttachment($uploadfile, $filename);
            if (!$mail->send()) 
            {
                $msg .= "Mailer Error: " . $mail->ErrorInfo;
            } 
            else 
            {
                $msg .= "Message sent!";
            }
        } 
            else 
            {
                $msg .= 'Failed to move file to ' . $uploadfile;
            }
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>PHPMailer Upload</title>
    </head>
    <body>
    <?php if (empty($msg)) { ?>
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="MAX_FILE_SIZE" value="4194304" />
            <input name="userfile" type="file">
            <input type="submit" value="Send File">
        </form>
    
    <?php } else {
        echo $msg;
    } ?>
    </body>
    </html>
    
    <form id='form'>
    <input type='file' name='file' />
    <input type='submit' />
    </form>
    
    $('#form').submit(function (e) {
    e.preventDefault();
    var formData = new FormData(this); // grab all form contents including files
    //you can then use formData and pass to ajax
    
    });
    
        <form method='post' enctype="multipart/form-data">
        <input type='file' name='uploaded_file' id='uploaded_file' multiple='multiple' />
        <input type='submit' name='upload'/> 
        </form>
    
        <?php
               if(isset($_POST['upload']))
            {
                 if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK)
                    {
                         if (array_key_exists('uploaded_file', $_FILES))
                            { 
                                $mail->Subject = "My Subject";
                                $mail->Body = 'This is the body';
                                $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['uploaded_file']['name']));
                            if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile))
                                 $mail->addAttachment($uploadfile,$_FILES['uploaded_file']['name']); 
                                $mail->send();
                                echo 'Message has been sent';
                            }       
                    else
                        echo "The file is not uploaded. please try again.";
                    }
                    else
                        echo "The file is not uploaded. please try again";
            }
        ?>