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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11764156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:00:44  来源:igfitidea点击:

Send File Attachment from Form Using phpMailer and PHP

phpfile-uploadphpmaileremail-attachments

提问by adamdehaven

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

我有一个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>

In my process.phpfile, I have the following code utilizing PHPMailer()to send an email:

在我的process.php文件中,我使用以下代码PHPMailer()发送电子邮件:

require("phpmailer.php");

$mail = new PHPMailer();

$mail->From     = [email protected];
$mail->FromName = My name;
$mail->AddAddress([email protected],"John Doe");

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

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

The email sends the body correctly, but without the Attachment of uploaded_file.

电子邮件正确发送正文,但没有附件uploaded_file

MY QUESTION

我的问题

I need the file uploaded_filefrom the form to be attached to the email, and sent. I do NOT care about saving the file after the process.phpscript sends it in an email.

我需要将uploaded_file表单中的文件附加到电子邮件中并发送。在process.php脚本通过电子邮件发送文件后,我不关心保存文件。

I understand that I need to add AddAttachment();somewhere (I'm assuming under the Bodyline) for the attachment to be sent. But...

我知道我需要在AddAttachment();某处添加(我假设在该Body行下)以发送附件。但...

  1. What do I put at the top of the process.phpfile to pull in the file uploaded_file? Like something using $_FILES['uploaded_file']to pull in the file from the contact-us.php page?
  2. What goes inside of AddAttachment();for the file to be attached and sent along with the email and where does this code need to go?
  1. 我在process.php文件顶部放什么来拉入文件uploaded_file?喜欢$_FILES['uploaded_file']从contact-us.php 页面拉入文件的东西吗?
  2. AddAttachment();要附加并与电子邮件一起发送的文件的内部内容以及此代码需要去哪里?

Please help and provide code!Thanks!

请帮忙并提供代码!谢谢!

回答by drew010

Try:

尝试:

if (isset($_FILES['uploaded_file']) &&
    $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
    $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);
}

Basic example can also be found here.

也可以在此处找到基本示例。

The function definition for AddAttachmentis:

的函数定义为AddAttachment

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

回答by Imtiaz Ahmad

File could not be Attached from client PC (upload)

无法从客户端 PC 附加文件(上传)

In the HTML form I have not added following line, so no attachment was going:

在 HTML 表单中,我没有添加以下行,因此没有附件:

enctype="multipart/form-data"

enctype="multipart/form-data"

After adding above line in form (as below), the attachment went perfect.

在表格中添加上一行后(如下),附件就完美了。

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

回答by Irshad Khan

This code help me in Attachment sending....

此代码帮助我发送附件....

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

Replace your AddAttachment(...) Code with above code

用上面的代码替换你的 AddAttachment(...) 代码

回答by JWC May

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

使用此代码在 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 = "[email protected]"; //[email protected]
            $mail->Password = "password";
            $mail->SetFrom("[email protected]", "Your Website Name");
            $mail->Subject = $subj;
            $mail->Body    = $new_body;

            $mail->AddAttachment($uploadfile);

            $mail->AltBody = 'Upload';
            $mail->AddAddress("[email protected]");
             if(!$mail->Send())
                {
                echo "Mailer Error: " . $mail->ErrorInfo;
                }
                else
                {

                echo '<p>       Success              </p> ';

                }

        }



?>

Use this linkfor reference.

使用此链接作为参考。

回答by pancy1

Hey guys the code below worked perfectly fine for me. Just replace the setFrom and addAddress with your preference and that's it.

嘿伙计们,下面的代码对我来说非常好。只需将 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('[email protected]', 'CV from Web site');
        $mail->addAddress('[email protected]', '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>

回答by Rotimi

In my own case, i was using serialize()on the form, Hence the files were not being sent to php. If you are using jquery, use FormData(). For example

在我自己的情况下,我serialize()在表单上使用,因此文件没有被发送到 php。如果您使用 jquery,请使用FormData(). 例如

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

Using jquery,

使用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

});

回答by Abdulhakim Zeinu

This will work perfectly

这将完美地工作

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

回答by Marc B

You'd use $_FILES['uploaded_file']['tmp_name'], which is the path where PHP stored the uploaded file (it's a temporary file, removed automatically by PHP when the script ends, unless you've moved/copied it elsewhere).

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

Assuming your client-side form and server-side upload settings are correct, there's nothing you have to do to "pull in" the upload. It'll just magically be available in that tmp_name path.

假设您的客户端表单和服务器端上传设置正确,您无需执行任何操作即可“拉入”上传。它会神奇地在 tmp_name 路径中可用。

Note that you WILL have to validate that the upload actually succeeded, e.g.

请注意,您必须验证上传是否实际成功,例如

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

Otherwise you may try to do an attachment with a damaged/partial/non-existent file.

否则,您可能会尝试使用损坏/部分/不存在的文件制作附件。