Nice programing

phpMailer 및 PHP를 사용하여 양식에서 파일 첨부 보내기

nicepro 2020. 11. 11. 20:37
반응형

phpMailer 및 PHP를 사용하여 양식에서 파일 첨부 보내기


example.com/contact-us.php다음과 같은 양식 이 있습니다 (간체).

<form method="post" action="process.php" enctype="multipart/form-data">
  <input type="file" name="uploaded_file" id="uploaded_file" />
  <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
</form>

process.php파일 PHPMailer()에는 이메일을 보내는 데 사용하는 다음 코드가 있습니다 .

require("phpmailer.php");

$mail = new PHPMailer();

$mail->From     = me@example.com;
$mail->FromName = My name;
$mail->AddAddress(me@example.com,"John Doe");

$mail->WordWrap = 50;
$mail->IsHTML(true);

$mail->Subject  =  "Contact Form Submitted";
$mail->Body     =  "This is the body of the message.";

이메일은 본문을 올바르게 보내지 만 uploaded_file.

내 질문

uploaded_file이메일에 첨부하여 보낼 양식 의 파일이 필요합니다 . process.php스크립트가 이메일로 파일을 보낸 후에는 파일을 저장하는 데 신경 쓰지 않습니다 .

첨부 파일을 보내려면 AddAttachment();어딘가에 추가해야한다는 것을 이해합니다 ( Body아래에 있다고 가정 합니다). 그러나...

  1. process.php파일을 가져 오기 위해 파일 맨 위에 무엇을 넣 uploaded_file습니까? $_FILES['uploaded_file']contact-us.php 페이지에서 파일을 가져 오는 데 사용 하는 것과 같은 가요?
  2. 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')

클라이언트 PC에서 파일을 첨부 할 수 없습니다 (업로드).

HTML 양식에서 다음 줄을 추가하지 않았으므로 첨부 파일이 없습니다.

enctype = "multipart / form-data"

(아래와 같이) 양식에 위의 줄을 추가하면 첨부 파일이 완벽 해졌습니다.

<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 (...) 코드를 위의 코드로 바꿉니다.


$_FILES['uploaded_file']['tmp_name']PHP가 업로드 된 파일을 저장 한 경로 인을 사용 합니다 (다른 곳으로 이동 / 복사하지 않는 한 스크립트가 끝날 때 PHP에 의해 자동으로 제거되는 임시 파일입니다).

클라이언트 측 양식과 서버 측 업로드 설정이 올바르다 고 가정하면 업로드를 "풀인"하기 위해 수행 할 작업이 없습니다. tmp_name 경로에서 마술처럼 사용할 수 있습니다.

업로드가 실제로 성공했는지 확인해야합니다. 예 :

if ($_FILES['uploaded_file']['error'] === UPLOAD_ERR_OK) {
    ... attach file to email ...
}

그렇지 않으면 손상된 / 일부 / 존재하지 않는 파일로 첨부를 시도 할 수 있습니다.


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를 기본 설정으로 바꾸면됩니다.

<?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>

제 경우 serialize()에는 양식 을 사용 하고 있었으므로 파일이 php로 전송되지 않았습니다. jquery를 사용하는 경우 FormData(). 예를 들면

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

jquery 사용,

$('#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";
        }
    ?>

참고URL : https://stackoverflow.com/questions/11764156/send-file-attachment-from-form-using-phpmailer-and-php

반응형