I have problem when I'm trying to send e-mail via form on my website with file attached. I'm using PHPMailer, mail is always sent, but always without attached file.
I have no idea what should I fix or add to my code.
I've been looking on some tutorials, how to use PHPMailer and attach files.
Code is below:
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");
}
}
?>