使用 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();里面有什么东西可以用来连接文件并随电子邮件一起发送,这些代码需要发送到哪里?

请帮助和提供代码! 谢谢!

226384 次浏览

试试:

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

附加多个文件上传的基本示例可以找到 给你

addAttachment的函数定义是:

/**
* Add an attachment from a path on the filesystem.
* Never use a user-supplied path to a file!
* Returns false if the file could not be found or read.
* Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
* If you need to do that, fetch the resource yourself and pass it in via a local file or string.
*
* @param string $path        Path to the attachment
* @param string $name        Overrides the attachment name
* @param string $encoding    File encoding (see $Encoding)
* @param string $type        MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
* @param string $disposition Disposition to use
*
* @throws Exception
*
* @return bool
*/
public function addAttachment(
$path,
$name = '',
$encoding = self::ENCODING_BASE64,
$type = '',
$disposition = 'attachment'
)

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

假设您的客户端表单和服务器端上传设置是正确的,那么您不需要做任何事情来“拉入”上传。它将神奇地出现在 tmp _ name 路径中。

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

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

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

无法从客户端 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']);

用上面的代码替换您的附件(...)代码

此代码用于使用 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";
}
?>