我正在尝试使用带有上传文件选项的HTML联系人表格,该选项应仅允许文件大小受限(<2MB)的.doc,.pdf和图像文件。我尝试了以下代码。对于DOC和IMG文件,它工作正常,但是如果我正在上传PDF,则不会发送电子邮件。
我正在HTML文件中使用AJAX并将其传递给PHP文件。
代码:
<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$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';
//Create a new PHPMailer instance
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "exampl@gmail.com";
$mail->Password = 'password';
$name = $_POST['name'];
$email = $_POST['email'];
$message .= "Name: ".($name)."\n";
$message .= "Email: ".($email)."\n";
$message .= "Message: ".$_POST['message'];
$mail->addAddress("example@gmail.com");
$mail->SetFrom($email, $name);
$mail->Subject = "Message from website";
$mail->Body = $message;
// $mail->MsgHTML($body);
// $mail->AddAddress($address, $name);
$mail->AddAttachment($uploadfile, $_FILES['userfile']['name'], $encoding = 'base64');
if($mail->Send()) {
echo "Message sent!";
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
?>