當我試圖通過附加文件的網站上的表單發送電子郵件時遇到問題。 我使用PHPMailer,郵件總是發送,但始終沒有附加文件。如何使用PHPMailer將文件附加到電子郵件
我不知道我應該修復或添加到我的代碼。
我一直在尋找一些教程,如何使用PHPMailer和附加文件。
代碼如下:
HTML:
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="name" style="width: 70%;" placeholder="Name"><br />
<input type="text" name="email" style="width: 70%;" placeholder="Email"><br />
<input type="text" name="phone" style="width: 70%;" placeholder="Phone"><br />
<input type="file" name="fileToUpload" id="fileToUpload"><br />
<input type="submit" name="send" id="gobutton" value="Send">
</form>
PHP:
<?
require_once("phpmailer/class.phpmailer.php");
if (isset($_POST['odeslat'])){
$allowedExts = array("doc", "docx", "xls", "xlsx", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword")
|| ($_FILES["file"]["type"] == "application/excel")
|| ($_FILES["file"]["type"] == "application/vnd.ms-excel")
|| ($_FILES["file"]["type"] == "application/x-excel")
|| ($_FILES["file"]["type"] == "application/x-msexcel")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "<script>alert('Error: " . $_FILES["file"]["error"] ."')</script>";
}
else
{
$d='upload/';
$de=$d . basename($_FILES['file']['name']);
move_uploaded_file($_FILES["file"]["tmp_name"], $de);
$fileName = $_FILES['file']['name'];
$filePath = $_FILES['file']['tmp_name'];
//add only if the file is an upload
}
}
else
{
echo "<script>alert('Invalid file')</script>";
}
$to = $_POST['email'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$mail = new PHPMailer();
$mail->From = "[email protected]";
$mail->FromName = "My website";
$mail->addAddress("[email protected]");
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
if(!$mail->send())
{
header ("Location: /?e=1");
}
else
{
header ("Location: /?s=1");
}
}
?>
您需要先查看'$ _FILES'超全局。這就是您可以在上傳的文件中找到數據的地方。看看[文檔](http://php.net/manual/en/features.file-upload.post-method.php)。 –
閱讀文檔和PHPmailer提供的示例。您在別處找到的建議很可能是錯誤的或過時的。 – Synchro