【发布时间】:2015-12-25 22:29:22
【问题描述】:
当我尝试通过我的网站上的表单发送电子邮件并附上文件时,我遇到了问题。 我正在使用 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 = "info@mywebsite.com";
$mail->FromName = "My website";
$mail->addAddress("mail@mail.com");
$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超全局。您可以在此处找到有关上传文件的数据。查看the documentation。 -
阅读 PHPmailer 提供的文档和示例。您在其他地方找到的建议可能是错误的或过时的。
标签: php email file-upload phpmailer email-attachments