Send File Attachment from Form Using phpMailer and PHP

后端 未结 8 952
予麋鹿
予麋鹿 2020-11-22 14:09

I have a form on example.com/contact-us.php that looks like this (simplified):

相关标签:
8条回答
  • 2020-11-22 15:05

    Use this code for sending attachment with upload file option using html form in phpmailer

     <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> ';
    
                    }
    
            }
    
    
    
    ?>
    

    Use this link for reference.

    0 讨论(0)
  • Hey guys the code below worked perfectly fine for me. Just replace the setFrom and addAddress with your preference and that's it.

    <?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>
    
    0 讨论(0)
提交回复
热议问题