Bootstrap 4 & Phpmailer form upload file












0















I think it's quite simple to realize but i really dont know where to start. What i would like is an option in the form where people can add an image or other file.



Ive added this in my bootstrap form:



<!--attachments-->
<div class="form-group">
<label for="attachment">Attachment</label>
<input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
</div>


So far so good i guess. But it wont send because there has to be something added in my phpmailer / send.php file. This is the script which i use now:



    <?php
require 'PHPMailerAutoload.php';

// Controleren of het formulier is verzonden dmv submit
if (isset($_POST['submitted'])) {

$errors = array(); // Initialize error array.

// Geef hier zoveel mogelijk vereiste velden voor validatie
//Add attachment
if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['attachmentFile']
['tmp_name'],$_FILES['attachmentFile']['name']);
}

// Controleer naam
if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['naam'])) {
$errors = 'Naam';
}

// Controleer adres
if (!preg_match("/^[a-zA-Z[:space:]]{1,}$/", $_POST['straat'])) {
$errors = 'Adres';
}

// Controleer huisnummer
if (!preg_match("/^[0-9]{1,4}$/", $_POST['huisnummer'])) {
$errors = 'Huisnummer';
}

// Controleer postcode
if (!preg_match("/^[0-9]{4}$/", $_POST['postcode'])) {
$errors = 'Postcode (Cijfers)';
}

// Controleer postcode letters
if (!preg_match("/^[a-zA-Z]{2}$/", $_POST['letters'])) {
$errors = 'Postcode (Letters)';
}

// Controleer woonplaats
if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['woonplaats'])) {
$errors = 'Woonplaats';
}

// Controleer Kengetal
if (!preg_match("/^[0]{1}[0-9]{1,3}$/", $_POST['kengetal'])) {
$errors = 'Kengetal';
}

// Controleer telefoonnummer
if (!preg_match("/^[0-9]{6,8}$/", $_POST['telefoon'])) {
$errors = 'Telefoonnummer';
}

// Controleer e-mail adres
if (!preg_match("/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)*.([a-zA-Z]{2,})$/", $_POST['email'])) {
$errors = 'E-mail adres';
}

// Controleer tekstvak
if (empty($_POST['bericht'])) {
$errors = 'Bericht';
}

if (empty($errors)) {

// Voer hier de gegevens in

$mailFrom = "myEmail";
$mailTo = "myEmail";
$senderNaam = $_POST['naam'];
$senderEmail = $_POST['email'];
$subject = 'mySubject';

$okMessage = '<p>blablabla</p>';
$errorMessage = '<p>blablabla</p>';

$emailText .= "Naam: " . $_POST['titel']." ". $_POST['naam']. "n";
$emailText .= "Bedrijfsnaam: " . $_POST['bedrijfsnaam']. "n";
$emailText .= "Adres: " . $_POST['straat']." ". $_POST['huisnummer']." ". $_POST['toevoeging']. "n";
$emailText .= "Postcode: " . $_POST['postcode']." ". $_POST['letters']. "n";
$emailText .= "Woonplaats: " . $_POST['woonplaats']. "n";
$emailText .= "Telefoonnummer: " . $_POST['kengetal']." ". $_POST['telefoon']. "n";
$emailText .= "E-mailadres: " . $_POST['email']. "n";
$emailText .= "Bericht: " . $_POST['bericht']. "n";

$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'SMTP SERVER'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'User'; // SMTP username
$mail->Password = 'Pass'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to


$mail->Sender = $mailFrom;
$mail->SetFrom($senderEmail, $senderNaam);
$mail->AddReplyTo($senderEmail, $senderNaam);
$mail->Subject = $subject;
$mail->MsgHTML($emailText);
$mail->AddAddress($mailTo, $mailTo);
$mail->addAttachment($uploadfile, 'My uploaded file'); **// ADDED THIS HERE**


$mail->isHTML(true); // Set email format to HTML

$mail->Subject = $subject;
$mail->Body = "<table>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Naam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['titel']." ".$_POST['naam']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bedrijfsnaam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bedrijfsnaam']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Adres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['straat']." ".$_POST['huisnummer']." ".$_POST['toevoeging']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Postcode:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['postcode']." ".$_POST['letters']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Woonplaats:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['woonplaats']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Telefoonnummer:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['kengetal']." ".$_POST['telefoon']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>E-mailadres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['email']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bericht:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bericht']."</td></tr>
</table>";

$mail->AltBody = $emailText;

if(!$mail->send()) {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
} else {
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);

header('Content-Type: application/json');

echo $encoded;
} else {
echo $responseArray['message'];
}

}
?>


Also added this to <form> enctype="multipart/form-data"



Edit #2: I also have a contact.js file with this:



data: $(this).serialize(),
I changed it in this:
data: new FormData(this),
Because i read somewhere that this could be the problem, but it didnt make sense.










share|improve this question

























  • Your code looks ok. To see how to handle a file upload, look at the example code provided with PHPMailer. One other thing - don't use the submitter's address as the from address; it's forgery and will cause SPF failures. Put your own address as the form address, and use the submitter's as a reply-to (as you're doing).

    – Synchro
    Nov 13 '18 at 14:03











  • Actually im not really good at this. So i dont know where to place what where.

    – Jorus
    Nov 13 '18 at 20:11











  • You’re going to need to actually try; your existing code is nearly there, so look at the differences between it and what is in the example I pointed you at.

    – Synchro
    Nov 14 '18 at 6:27











  • Alright, i made an edit above. It does send, but it doesnt send the attachment. No idea whats going wrong.

    – Jorus
    Nov 14 '18 at 9:39











  • For the record... I want people to send me a file, and not a file to them when they send it.

    – Jorus
    Nov 14 '18 at 9:48
















0















I think it's quite simple to realize but i really dont know where to start. What i would like is an option in the form where people can add an image or other file.



Ive added this in my bootstrap form:



<!--attachments-->
<div class="form-group">
<label for="attachment">Attachment</label>
<input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
</div>


So far so good i guess. But it wont send because there has to be something added in my phpmailer / send.php file. This is the script which i use now:



    <?php
require 'PHPMailerAutoload.php';

// Controleren of het formulier is verzonden dmv submit
if (isset($_POST['submitted'])) {

$errors = array(); // Initialize error array.

// Geef hier zoveel mogelijk vereiste velden voor validatie
//Add attachment
if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['attachmentFile']
['tmp_name'],$_FILES['attachmentFile']['name']);
}

// Controleer naam
if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['naam'])) {
$errors = 'Naam';
}

// Controleer adres
if (!preg_match("/^[a-zA-Z[:space:]]{1,}$/", $_POST['straat'])) {
$errors = 'Adres';
}

// Controleer huisnummer
if (!preg_match("/^[0-9]{1,4}$/", $_POST['huisnummer'])) {
$errors = 'Huisnummer';
}

// Controleer postcode
if (!preg_match("/^[0-9]{4}$/", $_POST['postcode'])) {
$errors = 'Postcode (Cijfers)';
}

// Controleer postcode letters
if (!preg_match("/^[a-zA-Z]{2}$/", $_POST['letters'])) {
$errors = 'Postcode (Letters)';
}

// Controleer woonplaats
if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['woonplaats'])) {
$errors = 'Woonplaats';
}

// Controleer Kengetal
if (!preg_match("/^[0]{1}[0-9]{1,3}$/", $_POST['kengetal'])) {
$errors = 'Kengetal';
}

// Controleer telefoonnummer
if (!preg_match("/^[0-9]{6,8}$/", $_POST['telefoon'])) {
$errors = 'Telefoonnummer';
}

// Controleer e-mail adres
if (!preg_match("/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)*.([a-zA-Z]{2,})$/", $_POST['email'])) {
$errors = 'E-mail adres';
}

// Controleer tekstvak
if (empty($_POST['bericht'])) {
$errors = 'Bericht';
}

if (empty($errors)) {

// Voer hier de gegevens in

$mailFrom = "myEmail";
$mailTo = "myEmail";
$senderNaam = $_POST['naam'];
$senderEmail = $_POST['email'];
$subject = 'mySubject';

$okMessage = '<p>blablabla</p>';
$errorMessage = '<p>blablabla</p>';

$emailText .= "Naam: " . $_POST['titel']." ". $_POST['naam']. "n";
$emailText .= "Bedrijfsnaam: " . $_POST['bedrijfsnaam']. "n";
$emailText .= "Adres: " . $_POST['straat']." ". $_POST['huisnummer']." ". $_POST['toevoeging']. "n";
$emailText .= "Postcode: " . $_POST['postcode']." ". $_POST['letters']. "n";
$emailText .= "Woonplaats: " . $_POST['woonplaats']. "n";
$emailText .= "Telefoonnummer: " . $_POST['kengetal']." ". $_POST['telefoon']. "n";
$emailText .= "E-mailadres: " . $_POST['email']. "n";
$emailText .= "Bericht: " . $_POST['bericht']. "n";

$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'SMTP SERVER'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'User'; // SMTP username
$mail->Password = 'Pass'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to


$mail->Sender = $mailFrom;
$mail->SetFrom($senderEmail, $senderNaam);
$mail->AddReplyTo($senderEmail, $senderNaam);
$mail->Subject = $subject;
$mail->MsgHTML($emailText);
$mail->AddAddress($mailTo, $mailTo);
$mail->addAttachment($uploadfile, 'My uploaded file'); **// ADDED THIS HERE**


$mail->isHTML(true); // Set email format to HTML

$mail->Subject = $subject;
$mail->Body = "<table>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Naam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['titel']." ".$_POST['naam']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bedrijfsnaam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bedrijfsnaam']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Adres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['straat']." ".$_POST['huisnummer']." ".$_POST['toevoeging']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Postcode:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['postcode']." ".$_POST['letters']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Woonplaats:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['woonplaats']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Telefoonnummer:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['kengetal']." ".$_POST['telefoon']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>E-mailadres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['email']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bericht:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bericht']."</td></tr>
</table>";

$mail->AltBody = $emailText;

if(!$mail->send()) {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
} else {
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);

header('Content-Type: application/json');

echo $encoded;
} else {
echo $responseArray['message'];
}

}
?>


Also added this to <form> enctype="multipart/form-data"



Edit #2: I also have a contact.js file with this:



data: $(this).serialize(),
I changed it in this:
data: new FormData(this),
Because i read somewhere that this could be the problem, but it didnt make sense.










share|improve this question

























  • Your code looks ok. To see how to handle a file upload, look at the example code provided with PHPMailer. One other thing - don't use the submitter's address as the from address; it's forgery and will cause SPF failures. Put your own address as the form address, and use the submitter's as a reply-to (as you're doing).

    – Synchro
    Nov 13 '18 at 14:03











  • Actually im not really good at this. So i dont know where to place what where.

    – Jorus
    Nov 13 '18 at 20:11











  • You’re going to need to actually try; your existing code is nearly there, so look at the differences between it and what is in the example I pointed you at.

    – Synchro
    Nov 14 '18 at 6:27











  • Alright, i made an edit above. It does send, but it doesnt send the attachment. No idea whats going wrong.

    – Jorus
    Nov 14 '18 at 9:39











  • For the record... I want people to send me a file, and not a file to them when they send it.

    – Jorus
    Nov 14 '18 at 9:48














0












0








0








I think it's quite simple to realize but i really dont know where to start. What i would like is an option in the form where people can add an image or other file.



Ive added this in my bootstrap form:



<!--attachments-->
<div class="form-group">
<label for="attachment">Attachment</label>
<input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
</div>


So far so good i guess. But it wont send because there has to be something added in my phpmailer / send.php file. This is the script which i use now:



    <?php
require 'PHPMailerAutoload.php';

// Controleren of het formulier is verzonden dmv submit
if (isset($_POST['submitted'])) {

$errors = array(); // Initialize error array.

// Geef hier zoveel mogelijk vereiste velden voor validatie
//Add attachment
if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['attachmentFile']
['tmp_name'],$_FILES['attachmentFile']['name']);
}

// Controleer naam
if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['naam'])) {
$errors = 'Naam';
}

// Controleer adres
if (!preg_match("/^[a-zA-Z[:space:]]{1,}$/", $_POST['straat'])) {
$errors = 'Adres';
}

// Controleer huisnummer
if (!preg_match("/^[0-9]{1,4}$/", $_POST['huisnummer'])) {
$errors = 'Huisnummer';
}

// Controleer postcode
if (!preg_match("/^[0-9]{4}$/", $_POST['postcode'])) {
$errors = 'Postcode (Cijfers)';
}

// Controleer postcode letters
if (!preg_match("/^[a-zA-Z]{2}$/", $_POST['letters'])) {
$errors = 'Postcode (Letters)';
}

// Controleer woonplaats
if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['woonplaats'])) {
$errors = 'Woonplaats';
}

// Controleer Kengetal
if (!preg_match("/^[0]{1}[0-9]{1,3}$/", $_POST['kengetal'])) {
$errors = 'Kengetal';
}

// Controleer telefoonnummer
if (!preg_match("/^[0-9]{6,8}$/", $_POST['telefoon'])) {
$errors = 'Telefoonnummer';
}

// Controleer e-mail adres
if (!preg_match("/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)*.([a-zA-Z]{2,})$/", $_POST['email'])) {
$errors = 'E-mail adres';
}

// Controleer tekstvak
if (empty($_POST['bericht'])) {
$errors = 'Bericht';
}

if (empty($errors)) {

// Voer hier de gegevens in

$mailFrom = "myEmail";
$mailTo = "myEmail";
$senderNaam = $_POST['naam'];
$senderEmail = $_POST['email'];
$subject = 'mySubject';

$okMessage = '<p>blablabla</p>';
$errorMessage = '<p>blablabla</p>';

$emailText .= "Naam: " . $_POST['titel']." ". $_POST['naam']. "n";
$emailText .= "Bedrijfsnaam: " . $_POST['bedrijfsnaam']. "n";
$emailText .= "Adres: " . $_POST['straat']." ". $_POST['huisnummer']." ". $_POST['toevoeging']. "n";
$emailText .= "Postcode: " . $_POST['postcode']." ". $_POST['letters']. "n";
$emailText .= "Woonplaats: " . $_POST['woonplaats']. "n";
$emailText .= "Telefoonnummer: " . $_POST['kengetal']." ". $_POST['telefoon']. "n";
$emailText .= "E-mailadres: " . $_POST['email']. "n";
$emailText .= "Bericht: " . $_POST['bericht']. "n";

$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'SMTP SERVER'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'User'; // SMTP username
$mail->Password = 'Pass'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to


$mail->Sender = $mailFrom;
$mail->SetFrom($senderEmail, $senderNaam);
$mail->AddReplyTo($senderEmail, $senderNaam);
$mail->Subject = $subject;
$mail->MsgHTML($emailText);
$mail->AddAddress($mailTo, $mailTo);
$mail->addAttachment($uploadfile, 'My uploaded file'); **// ADDED THIS HERE**


$mail->isHTML(true); // Set email format to HTML

$mail->Subject = $subject;
$mail->Body = "<table>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Naam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['titel']." ".$_POST['naam']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bedrijfsnaam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bedrijfsnaam']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Adres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['straat']." ".$_POST['huisnummer']." ".$_POST['toevoeging']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Postcode:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['postcode']." ".$_POST['letters']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Woonplaats:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['woonplaats']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Telefoonnummer:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['kengetal']." ".$_POST['telefoon']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>E-mailadres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['email']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bericht:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bericht']."</td></tr>
</table>";

$mail->AltBody = $emailText;

if(!$mail->send()) {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
} else {
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);

header('Content-Type: application/json');

echo $encoded;
} else {
echo $responseArray['message'];
}

}
?>


Also added this to <form> enctype="multipart/form-data"



Edit #2: I also have a contact.js file with this:



data: $(this).serialize(),
I changed it in this:
data: new FormData(this),
Because i read somewhere that this could be the problem, but it didnt make sense.










share|improve this question
















I think it's quite simple to realize but i really dont know where to start. What i would like is an option in the form where people can add an image or other file.



Ive added this in my bootstrap form:



<!--attachments-->
<div class="form-group">
<label for="attachment">Attachment</label>
<input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
</div>


So far so good i guess. But it wont send because there has to be something added in my phpmailer / send.php file. This is the script which i use now:



    <?php
require 'PHPMailerAutoload.php';

// Controleren of het formulier is verzonden dmv submit
if (isset($_POST['submitted'])) {

$errors = array(); // Initialize error array.

// Geef hier zoveel mogelijk vereiste velden voor validatie
//Add attachment
if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['attachmentFile']
['tmp_name'],$_FILES['attachmentFile']['name']);
}

// Controleer naam
if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['naam'])) {
$errors = 'Naam';
}

// Controleer adres
if (!preg_match("/^[a-zA-Z[:space:]]{1,}$/", $_POST['straat'])) {
$errors = 'Adres';
}

// Controleer huisnummer
if (!preg_match("/^[0-9]{1,4}$/", $_POST['huisnummer'])) {
$errors = 'Huisnummer';
}

// Controleer postcode
if (!preg_match("/^[0-9]{4}$/", $_POST['postcode'])) {
$errors = 'Postcode (Cijfers)';
}

// Controleer postcode letters
if (!preg_match("/^[a-zA-Z]{2}$/", $_POST['letters'])) {
$errors = 'Postcode (Letters)';
}

// Controleer woonplaats
if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['woonplaats'])) {
$errors = 'Woonplaats';
}

// Controleer Kengetal
if (!preg_match("/^[0]{1}[0-9]{1,3}$/", $_POST['kengetal'])) {
$errors = 'Kengetal';
}

// Controleer telefoonnummer
if (!preg_match("/^[0-9]{6,8}$/", $_POST['telefoon'])) {
$errors = 'Telefoonnummer';
}

// Controleer e-mail adres
if (!preg_match("/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)*.([a-zA-Z]{2,})$/", $_POST['email'])) {
$errors = 'E-mail adres';
}

// Controleer tekstvak
if (empty($_POST['bericht'])) {
$errors = 'Bericht';
}

if (empty($errors)) {

// Voer hier de gegevens in

$mailFrom = "myEmail";
$mailTo = "myEmail";
$senderNaam = $_POST['naam'];
$senderEmail = $_POST['email'];
$subject = 'mySubject';

$okMessage = '<p>blablabla</p>';
$errorMessage = '<p>blablabla</p>';

$emailText .= "Naam: " . $_POST['titel']." ". $_POST['naam']. "n";
$emailText .= "Bedrijfsnaam: " . $_POST['bedrijfsnaam']. "n";
$emailText .= "Adres: " . $_POST['straat']." ". $_POST['huisnummer']." ". $_POST['toevoeging']. "n";
$emailText .= "Postcode: " . $_POST['postcode']." ". $_POST['letters']. "n";
$emailText .= "Woonplaats: " . $_POST['woonplaats']. "n";
$emailText .= "Telefoonnummer: " . $_POST['kengetal']." ". $_POST['telefoon']. "n";
$emailText .= "E-mailadres: " . $_POST['email']. "n";
$emailText .= "Bericht: " . $_POST['bericht']. "n";

$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'SMTP SERVER'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'User'; // SMTP username
$mail->Password = 'Pass'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to


$mail->Sender = $mailFrom;
$mail->SetFrom($senderEmail, $senderNaam);
$mail->AddReplyTo($senderEmail, $senderNaam);
$mail->Subject = $subject;
$mail->MsgHTML($emailText);
$mail->AddAddress($mailTo, $mailTo);
$mail->addAttachment($uploadfile, 'My uploaded file'); **// ADDED THIS HERE**


$mail->isHTML(true); // Set email format to HTML

$mail->Subject = $subject;
$mail->Body = "<table>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Naam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['titel']." ".$_POST['naam']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bedrijfsnaam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bedrijfsnaam']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Adres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['straat']." ".$_POST['huisnummer']." ".$_POST['toevoeging']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Postcode:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['postcode']." ".$_POST['letters']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Woonplaats:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['woonplaats']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Telefoonnummer:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['kengetal']." ".$_POST['telefoon']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>E-mailadres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['email']."</td></tr>
<tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bericht:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bericht']."</td></tr>
</table>";

$mail->AltBody = $emailText;

if(!$mail->send()) {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
} else {
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);

header('Content-Type: application/json');

echo $encoded;
} else {
echo $responseArray['message'];
}

}
?>


Also added this to <form> enctype="multipart/form-data"



Edit #2: I also have a contact.js file with this:



data: $(this).serialize(),
I changed it in this:
data: new FormData(this),
Because i read somewhere that this could be the problem, but it didnt make sense.







forms twitter-bootstrap-3 bootstrap-4 phpmailer






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 12:11







Jorus

















asked Nov 13 '18 at 12:54









JorusJorus

5511




5511













  • Your code looks ok. To see how to handle a file upload, look at the example code provided with PHPMailer. One other thing - don't use the submitter's address as the from address; it's forgery and will cause SPF failures. Put your own address as the form address, and use the submitter's as a reply-to (as you're doing).

    – Synchro
    Nov 13 '18 at 14:03











  • Actually im not really good at this. So i dont know where to place what where.

    – Jorus
    Nov 13 '18 at 20:11











  • You’re going to need to actually try; your existing code is nearly there, so look at the differences between it and what is in the example I pointed you at.

    – Synchro
    Nov 14 '18 at 6:27











  • Alright, i made an edit above. It does send, but it doesnt send the attachment. No idea whats going wrong.

    – Jorus
    Nov 14 '18 at 9:39











  • For the record... I want people to send me a file, and not a file to them when they send it.

    – Jorus
    Nov 14 '18 at 9:48



















  • Your code looks ok. To see how to handle a file upload, look at the example code provided with PHPMailer. One other thing - don't use the submitter's address as the from address; it's forgery and will cause SPF failures. Put your own address as the form address, and use the submitter's as a reply-to (as you're doing).

    – Synchro
    Nov 13 '18 at 14:03











  • Actually im not really good at this. So i dont know where to place what where.

    – Jorus
    Nov 13 '18 at 20:11











  • You’re going to need to actually try; your existing code is nearly there, so look at the differences between it and what is in the example I pointed you at.

    – Synchro
    Nov 14 '18 at 6:27











  • Alright, i made an edit above. It does send, but it doesnt send the attachment. No idea whats going wrong.

    – Jorus
    Nov 14 '18 at 9:39











  • For the record... I want people to send me a file, and not a file to them when they send it.

    – Jorus
    Nov 14 '18 at 9:48

















Your code looks ok. To see how to handle a file upload, look at the example code provided with PHPMailer. One other thing - don't use the submitter's address as the from address; it's forgery and will cause SPF failures. Put your own address as the form address, and use the submitter's as a reply-to (as you're doing).

– Synchro
Nov 13 '18 at 14:03





Your code looks ok. To see how to handle a file upload, look at the example code provided with PHPMailer. One other thing - don't use the submitter's address as the from address; it's forgery and will cause SPF failures. Put your own address as the form address, and use the submitter's as a reply-to (as you're doing).

– Synchro
Nov 13 '18 at 14:03













Actually im not really good at this. So i dont know where to place what where.

– Jorus
Nov 13 '18 at 20:11





Actually im not really good at this. So i dont know where to place what where.

– Jorus
Nov 13 '18 at 20:11













You’re going to need to actually try; your existing code is nearly there, so look at the differences between it and what is in the example I pointed you at.

– Synchro
Nov 14 '18 at 6:27





You’re going to need to actually try; your existing code is nearly there, so look at the differences between it and what is in the example I pointed you at.

– Synchro
Nov 14 '18 at 6:27













Alright, i made an edit above. It does send, but it doesnt send the attachment. No idea whats going wrong.

– Jorus
Nov 14 '18 at 9:39





Alright, i made an edit above. It does send, but it doesnt send the attachment. No idea whats going wrong.

– Jorus
Nov 14 '18 at 9:39













For the record... I want people to send me a file, and not a file to them when they send it.

– Jorus
Nov 14 '18 at 9:48





For the record... I want people to send me a file, and not a file to them when they send it.

– Jorus
Nov 14 '18 at 9:48












1 Answer
1






active

oldest

votes


















0














Alright, the form is sending with attachments! There is only one little thing i hope someone can help me with that.. more about this later on. First the code.



In contact.js - I had to change data: $(this).serialize(), into data: new FormData(this),



    $(function () {

$('#contact-form').validator();

$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "send.php";

$.ajax({
type: "POST",
url: url,
data: new FormData(this),
cache : false,
contentType : false,
processData : false,
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;

var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset(); //Remove this line if form should not reset after submit
$('body, html').animate({scrollTop:$('#contact-form').offset().top}, 'fast'); //Remove this line if form should not scroll to top of the form after submit
}
}
});
return false;
}
})
});


Myform.html - 2 things: this enctype="multipart/form-data" in <form>, and this



    <!--attachments-->
<div class="form-group">
<label for="attachment">Attachment</label>
<input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
</div>


somewhere you want in the form.



Finally put this in your phpmailer file:



    //Add attachment
if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']);
}


I did it below $mail->AddAddress($mailTo, $mailTo);



So far how to fix this. There is still one problem left i refer to in the beginning.



Without data: new FormData(this), I still get my okMessage (with markup) when i hit send and the form stays at the same page.



With data: new FormData(this), it goes to a new page and just give black on white plain text (without markup).
So its like FormData is overruling something. Hope someone can help me out with this.



EDIT: Seems i have fixed this too. Place this..



cache       : false,
contentType : false,
processData : false,


..below data: new FormData(this),






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53281479%2fbootstrap-4-phpmailer-form-upload-file%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Alright, the form is sending with attachments! There is only one little thing i hope someone can help me with that.. more about this later on. First the code.



    In contact.js - I had to change data: $(this).serialize(), into data: new FormData(this),



        $(function () {

    $('#contact-form').validator();

    $('#contact-form').on('submit', function (e) {
    if (!e.isDefaultPrevented()) {
    var url = "send.php";

    $.ajax({
    type: "POST",
    url: url,
    data: new FormData(this),
    cache : false,
    contentType : false,
    processData : false,
    success: function (data)
    {
    var messageAlert = 'alert-' + data.type;
    var messageText = data.message;

    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
    if (messageAlert && messageText) {
    $('#contact-form').find('.messages').html(alertBox);
    $('#contact-form')[0].reset(); //Remove this line if form should not reset after submit
    $('body, html').animate({scrollTop:$('#contact-form').offset().top}, 'fast'); //Remove this line if form should not scroll to top of the form after submit
    }
    }
    });
    return false;
    }
    })
    });


    Myform.html - 2 things: this enctype="multipart/form-data" in <form>, and this



        <!--attachments-->
    <div class="form-group">
    <label for="attachment">Attachment</label>
    <input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
    </div>


    somewhere you want in the form.



    Finally put this in your phpmailer file:



        //Add attachment
    if(is_array($_FILES)) {
    $mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']);
    }


    I did it below $mail->AddAddress($mailTo, $mailTo);



    So far how to fix this. There is still one problem left i refer to in the beginning.



    Without data: new FormData(this), I still get my okMessage (with markup) when i hit send and the form stays at the same page.



    With data: new FormData(this), it goes to a new page and just give black on white plain text (without markup).
    So its like FormData is overruling something. Hope someone can help me out with this.



    EDIT: Seems i have fixed this too. Place this..



    cache       : false,
    contentType : false,
    processData : false,


    ..below data: new FormData(this),






    share|improve this answer






























      0














      Alright, the form is sending with attachments! There is only one little thing i hope someone can help me with that.. more about this later on. First the code.



      In contact.js - I had to change data: $(this).serialize(), into data: new FormData(this),



          $(function () {

      $('#contact-form').validator();

      $('#contact-form').on('submit', function (e) {
      if (!e.isDefaultPrevented()) {
      var url = "send.php";

      $.ajax({
      type: "POST",
      url: url,
      data: new FormData(this),
      cache : false,
      contentType : false,
      processData : false,
      success: function (data)
      {
      var messageAlert = 'alert-' + data.type;
      var messageText = data.message;

      var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
      if (messageAlert && messageText) {
      $('#contact-form').find('.messages').html(alertBox);
      $('#contact-form')[0].reset(); //Remove this line if form should not reset after submit
      $('body, html').animate({scrollTop:$('#contact-form').offset().top}, 'fast'); //Remove this line if form should not scroll to top of the form after submit
      }
      }
      });
      return false;
      }
      })
      });


      Myform.html - 2 things: this enctype="multipart/form-data" in <form>, and this



          <!--attachments-->
      <div class="form-group">
      <label for="attachment">Attachment</label>
      <input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
      </div>


      somewhere you want in the form.



      Finally put this in your phpmailer file:



          //Add attachment
      if(is_array($_FILES)) {
      $mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']);
      }


      I did it below $mail->AddAddress($mailTo, $mailTo);



      So far how to fix this. There is still one problem left i refer to in the beginning.



      Without data: new FormData(this), I still get my okMessage (with markup) when i hit send and the form stays at the same page.



      With data: new FormData(this), it goes to a new page and just give black on white plain text (without markup).
      So its like FormData is overruling something. Hope someone can help me out with this.



      EDIT: Seems i have fixed this too. Place this..



      cache       : false,
      contentType : false,
      processData : false,


      ..below data: new FormData(this),






      share|improve this answer




























        0












        0








        0







        Alright, the form is sending with attachments! There is only one little thing i hope someone can help me with that.. more about this later on. First the code.



        In contact.js - I had to change data: $(this).serialize(), into data: new FormData(this),



            $(function () {

        $('#contact-form').validator();

        $('#contact-form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
        var url = "send.php";

        $.ajax({
        type: "POST",
        url: url,
        data: new FormData(this),
        cache : false,
        contentType : false,
        processData : false,
        success: function (data)
        {
        var messageAlert = 'alert-' + data.type;
        var messageText = data.message;

        var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
        if (messageAlert && messageText) {
        $('#contact-form').find('.messages').html(alertBox);
        $('#contact-form')[0].reset(); //Remove this line if form should not reset after submit
        $('body, html').animate({scrollTop:$('#contact-form').offset().top}, 'fast'); //Remove this line if form should not scroll to top of the form after submit
        }
        }
        });
        return false;
        }
        })
        });


        Myform.html - 2 things: this enctype="multipart/form-data" in <form>, and this



            <!--attachments-->
        <div class="form-group">
        <label for="attachment">Attachment</label>
        <input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
        </div>


        somewhere you want in the form.



        Finally put this in your phpmailer file:



            //Add attachment
        if(is_array($_FILES)) {
        $mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']);
        }


        I did it below $mail->AddAddress($mailTo, $mailTo);



        So far how to fix this. There is still one problem left i refer to in the beginning.



        Without data: new FormData(this), I still get my okMessage (with markup) when i hit send and the form stays at the same page.



        With data: new FormData(this), it goes to a new page and just give black on white plain text (without markup).
        So its like FormData is overruling something. Hope someone can help me out with this.



        EDIT: Seems i have fixed this too. Place this..



        cache       : false,
        contentType : false,
        processData : false,


        ..below data: new FormData(this),






        share|improve this answer















        Alright, the form is sending with attachments! There is only one little thing i hope someone can help me with that.. more about this later on. First the code.



        In contact.js - I had to change data: $(this).serialize(), into data: new FormData(this),



            $(function () {

        $('#contact-form').validator();

        $('#contact-form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
        var url = "send.php";

        $.ajax({
        type: "POST",
        url: url,
        data: new FormData(this),
        cache : false,
        contentType : false,
        processData : false,
        success: function (data)
        {
        var messageAlert = 'alert-' + data.type;
        var messageText = data.message;

        var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
        if (messageAlert && messageText) {
        $('#contact-form').find('.messages').html(alertBox);
        $('#contact-form')[0].reset(); //Remove this line if form should not reset after submit
        $('body, html').animate({scrollTop:$('#contact-form').offset().top}, 'fast'); //Remove this line if form should not scroll to top of the form after submit
        }
        }
        });
        return false;
        }
        })
        });


        Myform.html - 2 things: this enctype="multipart/form-data" in <form>, and this



            <!--attachments-->
        <div class="form-group">
        <label for="attachment">Attachment</label>
        <input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
        </div>


        somewhere you want in the form.



        Finally put this in your phpmailer file:



            //Add attachment
        if(is_array($_FILES)) {
        $mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']);
        }


        I did it below $mail->AddAddress($mailTo, $mailTo);



        So far how to fix this. There is still one problem left i refer to in the beginning.



        Without data: new FormData(this), I still get my okMessage (with markup) when i hit send and the form stays at the same page.



        With data: new FormData(this), it goes to a new page and just give black on white plain text (without markup).
        So its like FormData is overruling something. Hope someone can help me out with this.



        EDIT: Seems i have fixed this too. Place this..



        cache       : false,
        contentType : false,
        processData : false,


        ..below data: new FormData(this),







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 10:32

























        answered Nov 15 '18 at 9:53









        JorusJorus

        5511




        5511






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53281479%2fbootstrap-4-phpmailer-form-upload-file%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Danny Elfman

            Lugert, Oklahoma