首页 > 解决方案 > 文件附件失败

问题描述

您好我正在尝试使用 phpmailer lib 发送邮件,并可选择附加多个文件。但是我的邮件脚本不发送邮件。
我已经使用类似的脚本成功发送邮件。但是当我尝试使用附件时它失败了。我遵循了 PHPmailer 示例。(我在这个表格中使用recaptcha 3。)
如果可能,请看一下,让我知道我可能做错了什么。
提前非常感谢。

html文件

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Multiple File Upload</title>
</head>
<body>

    <form method="post" id="contact-form" enctype="multipart/form-data" action="testmailer.php">
        <input name="fname" placeholder="Your name" title="Your name" type="text" /></div>
        Select one or more files:
        <input name="userfile[]" type="file" multiple="multiple">
        <input type="hidden" name="recaptcha_response" id="recaptchaResponse">
        <input type="submit" id="submit-button" value="Send Files">
        <div id="alertm"></div>
    </form>

    <script>
        $('#contact-form').submit(function(event) {
            event.preventDefault(); 
            $('#alertm').text('Processing...').fadeIn(0); 
            grecaptcha.ready(function () {
                grecaptcha.execute('xxxrecaptcha3-site_keyxxx', { action: 'contact' }).then(function (token) {
                    var recaptchaResponse = document.getElementById('recaptchaResponse');
                    recaptchaResponse.value = token;
                    // Make the Ajax call here
                    $.ajax({
                        url: 'testmailer.php',
                        type: 'post',
                        data: $('#contact-form').serialize(),
                        dataType: 'json',
                        success: function( _response ){
                            // The Ajax request is a success. _response is a JSON object
                            var error = _response.error;
                            var success = _response.success;
                            if(error != "") {
                                // In case of error, display it to user
                                $('#alertm').html(error);
                            }
                            else {
                                // In case of success, display it to user and remove the submit button
                                $('#alertm').html(success);
                                $('#submit-button').remove();
                            }
                        },
                        error: function(jqXhr, json, errorThrown){
                            // In case of Ajax error too, display the result
                            var error = jqXhr.responseText;
                            $('#alertm').html(error);
                        }
                    });
                });
            });
        });
    </script>
</body>
</html>

邮件发送脚本


    <?php
    
    require $_SERVER['DOCUMENT_ROOT'] . '/PHPMailer/src/PHPMailer.php';
    use PHPMailer\PHPMailer\PHPMailer;
    $mail = new PHPMailer();

    if(isset($_POST['fname'])){
        $name=$_POST['fname'];
    }
    function isValid() {
        if($_POST['name'] != "") {
            return true;
        } else {
            return false;
        }
    }
    $email_to = "email@domain.com"; 
    $mail->setFrom('no-reply@somedomain.com', 'SomeDomain Mailer');
    $mail->Subject = 'File Attachment';
    $body = "Name - $name\n";
    $mail->Body = $body;
    
    if (array_key_exists('userfile', $_FILES)) { 
        
        for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
            $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name'][$ct]));
            $filename = $_FILES['userfile']['name'][$ct];
            if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
                if (!$mail->addAttachment($uploadfile, $filename)) {
                    $msg .= 'Failed to attach file ' . $filename;
                   }
            } else {
                $body .= 'Failed to move file to ' . $uploadfile;
            }
        }
        $mail->IsHTML(true);
    
        $error_output = '';
        $success_output = '';
    
    if(isValid()) {
        $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
        $recaptcha_secret = '***recaptcha3-secret_key***'; 
        $recaptcha_response = $_POST['recaptcha_response'];
    
        $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
        $recaptcha = json_decode($recaptcha);
    
        if ($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == 'contact') {
            $mail->send();
            $success_output = "Your message sent successfully";
        } else {
            $error_output = "Something went wrong. Please try again later";
        }
    } else {
        $error_output = "Please fill all the required fields";
    }
    
    $output = array(
        'error'     =>  $error_output,
        'success'   =>  $success_output
    );
    // Output needs to be in JSON format
    echo json_encode($output);
    }
    ?>

标签: phpphpmailer

解决方案


推荐阅读