I am having trouble getting form to send attachments. It will either hang up or not send them and the error file shows nothing. Site is on a shared hosting server. The form works without attachments.
I am not a coder but i have searched this site and most of the information i have found refers to editing files created by composer which i am not using. Do I need to need to create a temp folder for the files before they are attached and if I do where do I define the path? The php code below is what I found for multiple attachments without composer and have been trying to adapt without success. Below is the code for attaching the file in the html form (I can post the entire html form if needed but since it works i did not see the need) and the php mail file any help would be appreciated.
<div class="form-group">
<label class="control-label col-sm-2" for="lname">Attach File:</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="attachFile" name="attachFile[]" multiple="multiple">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="comment">Message:</label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" name="message" id="message"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="sendEmail">Send Email</button>
-------------------------------------------------------------------------------------------------------------------
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once 'PHPMailer/PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/PHPMailer/src/SMTP.php';
$msg = ''; // start with a blank message
$msg .= 'Email: ' . $_POST['email'] . "\n";
$msg .= 'City: ' . $_POST['city'] . "\n";
$msg .= 'State: ' . $_POST['state'] . "\n";
$msg .= 'Telephone: ' . $_POST['phone'] . "\n";
$msg .= 'Message: ' . $_POST['message'] . "\n";
if (array_key_exists('attachFile', $_FILES)) {
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = 'mail.domain.com'; // SMTP server
$mail->Username = 'form#domain.com';
$mail->Password = 'password';
$mail->setFrom ('form#domain.com');
$mail->AddAddress ('user#domain.com');
$mail->Subject = "Info Request";
$mail->Body = $msg;
$mail->WordWrap = 50;
# $mail->Port = 465;
for ($ct = 0, $ctMax = count($_FILES['attachFile']['tmp_name']); $ct < $ctMax; $ct++) {
//Extract an extension from the provided filename
$ext = PHPMailer::mb_pathinfo($_FILES['attachFile']['name'][$ct], PATHINFO_EXTENSION);
//Define a safe location to move the uploaded file to, preserving the extension
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachFile']['name'][$ct])) . '.' . $ext;
$filename = $_FILES['attachFile']['name'][$ct];
if (move_uploaded_file($_FILES['attachFile']['tmp_name'][$ct], $uploadfile)) {
if (!$mail->addAttachment($uploadfile, $filename)) {
$msg .= 'Failed to attach file ' . $filename;
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
if (!$mail->send()) {
$msg .= 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$msg .= 'Message sent!';
}
}
# $return = $mail->Send();
?>
<html>
<head>
//<meta HTTP-EQUIV="refresh" Content="0;url=thankyou.html">
</head>
<body bgcolor="#366A7F">
</body>
</html>
Related
The code below used to work fine a while ago, sending emails with images to Blogger's email; or sending emails to any provided email address. Unfortunately I have no idea when it stopped working and how to fix it. The error given is
Array ( [type] => 2 [message] => preg_match() expects parameter 2 to be string, array given [file] => /var/www/html/PHPMailer.php [line] => 4533 )
Below is the page, I appreciate if someone could fix it.
<?php
// error_reporting(0);
// ini_set('display_errors', 0);
var_dump($_POST["name"]);
var_dump($_POST["age"]);
var_dump($_FILES);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$error = '';
$name = '';
$age = '';
$email = '';
$subject = '';
$country = '';
$message = '';
$msg = '';
$youtube = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
//age
if(empty($_POST["age"]))
{
$error .= '<p><label class="text-danger">Please Enter your Age</label></p>';
}
else
{
$age = clean_text($_POST["age"]);
if(!preg_match("/^[0-9]*$/",$age))
{
$error .= '<p><label class="text-danger">Only numbers allowed</label></p>';
}
}
//age
//i am
if(empty($_POST['formGender']))
{
$error .= '<p><label class="text-danger">Select your gender</label></p>';
}
//i am
//looking for
if(empty($_POST['formGender2']))
{
$error .= '<p><label class="text-danger">Select your Partner</label></p>';
}
//looking for
//for
if(empty($_POST['formGender3']))
{
$error .= '<p><label class="text-danger">Select your preferences</label></p>';
}
//for
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">City/Town is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
//country
if(empty($_POST["country"]))
{
$error .= '<p><label class="text-danger">Country is required</label></p>';
}
else
{
$subject = clean_text($_POST["country"]);
}
//country
if(empty($_POST["youtube"]))
{
// $error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$youtube = clean_text($_POST["youtube"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if(empty($_POST["phone"]))
{
// $error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$phone = clean_text($_POST["phone"]);
}
if($error == '')
{
if (array_key_exists('userfile', $_FILES)) {
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$ip = $_SERVER['REMOTE_ADDR'];
require 'Exception.php';
require 'PHPMailer.php';
require 'SMTP.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = 'smtp.gmail.com'; //Sets the SMTP hosts
$mail->Port = '465'; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = 'asdfdfgndfbgasdf'; //Sets SMTP username
$mail->Password = 'asdfsgdbfsfg'; //Sets SMTP password
$mail->SMTPSecure = 'ssl'; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = $_POST["email"]; //Sets the From email address for the message
$mail->FromName = $_POST["name"]; //Sets the From name of the message
$mail->AddAddress('asdfasdf.dfnghdfghfgh#blogger.com', 'Name');//Adds a "To" address
$mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
$mail->WordWrap = 1000; //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->Subject = $_POST["name"] . ', ' . $_POST['formGender'] . ' (' . $_POST["age"] . ') looking to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"]; //Sets the Subject of the message
if(empty($_POST["youtube"]))
{
$mail->Body = '<div id="intro"> Meet <span style="text-transform: capitalize;">' . $_POST["name"] . '</span>, a ' . $_POST["age"] . ' yo ' . $_POST["formGender"] . ' looking for ' . $_POST["formGender2"] . ' to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"] . '. If you want to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ', ' . $_POST["country"] . ', leave a message for ' . $_POST["name"] . ' on this page or use the contact details below.<br/><br/><strong>Email</strong> ' . $_POST["email"] . ' <br/><strong>Phone</strong> ' . $_POST["phone"] . '.</div><div id="beforeblock">... more about ' . $_POST["name"] . ' below, in their own words: </div><div style="clear:both;"></div><blockquote>' . $_POST["message"] . '</blockquote><div id="regip">Profile registered from IP <strong>' . $ip . '</strong></div><iframe width="600" height="500" id="gmap_canvas" src="https://maps.google.com/maps?q=' . $_POST['subject'] . ',' . $_POST['country'] . '&t=&z=10&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" loading="lazy" style="width:100%;max-width:100%;height:auto;min-height:315px;"></iframe><br/><span id="tags">' . $_POST['formGender'] . ', ' . $_POST['subject'] . ', ' . $_POST['country'] . '</span>'; //An HTML or plain text message body
}
if($_POST["youtube"])
{
$mail->Body = '<div id="intro"> Meet <span style="text-transform: capitalize;">' . $_POST["name"] . '</span>, a ' . $_POST["age"] . ' yo ' . $_POST["formGender"] . ' looking for ' . $_POST["formGender2"] . ' to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"] . '. If you want to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ', ' . $_POST["country"] . ', leave a message for ' . $_POST["name"] . ' on this page or use the contact details below.<br/><br/><strong>Email</strong> ' . $_POST["email"] . ' <br/><strong>Phone</strong> ' . $_POST["phone"] . '.</div><div id="beforeblock">... more about ' . $_POST["name"] . ' below, in their own words: </div><div style="clear:both;"></div><blockquote>' . $_POST["message"] . '</blockquote><iframe loading="lazy" style="width:100%;min-height:315px;height:auto;margin:0 5px;" width="560" height="315" src="https://www.youtube.com/embed/' . $_POST["youtube"] . '" title="Video" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" id="youtubeframe" allowfullscreen></iframe><div id="regip">Profile registered from IP <strong>' . $ip . '</strong></div><iframe width="600" height="500" id="gmap_canvas" src="https://maps.google.com/maps?q=' . $_POST['subject'] . ',' . $_POST['country'] . '&t=&z=10&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" loading="lazy" style="width:100%;max-width:100%;height:auto;min-height:200px;"></iframe><br/><span id="tags">' . $_POST['formGender'] . ', ' . $_POST['subject'] . ', ' . $_POST['country'] . '</span>'; //An HTML or plain text message body
}
$mail->set('X-Priority', '3'); //Priority 1 = High, 3 = Normal, 5 = low
//photo
//Attach multiple files one by one
for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
//Extract an extension from the provided filename
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
//Define a safe location to move the uploaded file to, preserving the extension
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct])) . '.' . $ext;
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
if (!$mail->addAttachment($uploadfile, $filename)) {
$msg .= 'Failed to upload the photos ' . $filename;
}
} else {
$msg .= 'Failed to move photo to ' . $uploadfile;
}
}
// $mail->AddAttachment($image_location);
//photos
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$error = '<label class="text-success">Thank you for registering your profile. It will be visible soon after aproval.</label><style>.form-container {display:none!important;}</style>';
}
else
{
$error = '<label class="text-danger">Your profile was not registered. Please try again!</label>';
// $errorMessage = error_get_last()['message'];
// echo $errorMessage;
// var_dump($_FILES);
print_r(error_get_last());
}
$name = '';
$age = '';
$email = '';
$subject = '';
$country = '';
$message = '';
$msg = '';
$youtube = '';
} //if img check ends
} //if error ends
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
.form-container{width:96%;MAX-WIDTH:96%;margin:0 2%;}
.form-group{margin-bottom:10px}
.btn{background:#1c94ff;padding:4px 8px;border:none;box-shadow:2px 1px 1px #d3d3d3;color:#fff;outline:0;font-size:17px;cursor:pointer;width:100%}
label{display:block;margin-bottom:2px}
.form-group .form-control{width:100%;outline:0;padding:5px;border:none;background:#d1d1d1;border-bottom:2px solid #1c94ff;font-size:16px}
.has-success .form-control{border-bottom:2px solid #168b3f}
.has-danger .form-control{border-bottom:2px solid #dc1d34}
.form-group .text-help{color:#dc1d34}
.inline-label label{display:inline}
.pristine-error{display:table}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined'){
document.write(unescape("%3Cscript src='//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
</head>
<body>
<?php echo $error; ?>
<div style="float:right;font-style: italic;"><span style="color:red;font-style: normal;">!</span> = mandatory</div>
<div class="form-container">
<form method="post" enctype="multipart/form-data" id="registercafebar">
<div class="form-group">
<label><span style="color:red">!</span> Name</label>
<input type="text" name="name" required minlength="3" maxlength="20" placeholder="Enter Your Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> Age</label>
<input required type="number" minlength="2" maxlength="2" min="16" max="99" name="age" placeholder="Enter your real age" class="form-control" value="<?php echo $age; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> I am a</label>
<select required name="formGender" class="form-control">
<option value="">Select your gender at birth</option>
<option value="woman">Woman</option>
<option value="man">Man</option>
</select>
</div>
<div class="form-group">
<label><span style="color:red">!</span> Looking for a</label>
<select name="formGender2" required class="form-control">
<option value="">Select who you are looking for</option>
<option value="man">Man</option>
<option value="woman">Woman</option>
<option value="couples">Couple</option>
</select>
</div>
<div class="form-group">
<label><span style="color:red">!</span> For</label>
<select name="formGender3" required class="form-control">
<option value="">Select what your intentions are</option>
<option value="date">Dating</option>
<option value="chat">Chat</option>
<option value="marry">Marriage</option>
<option value="have sex">Sex</option>
</select>
</div>
<div class="form-group">
<label><span style="color:red">!</span> City</label>
<input type="text" name="subject" required class="form-control" minlength="2" maxlength="25" placeholder="Enter your City/Town" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> Country</label>
<input type="text" name="country" required class="form-control" minlength="2" maxlength="20" placeholder="Enter your Country" value="<?php echo $country; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> About me </label>
<textarea name="message" cols="30" rows="5" minlength="200" maxlength="1000" required class="form-control" placeholder="Describe who you are and what you are looking for, write about the things you like or dislike or talk about your hobbies, but keep it spam free."><?php echo $message; ?></textarea>
</div>
<div class="form-group">
<label><span style="color:red">!</span> Email</label>
<input type="email" name="email" class="form-control" minlength="6" maxlength="30" required placeholder="Enter Your Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" name="phone" class="form-control" minlength="4" maxlength="25" placeholder="Enter Your Phone" value="<?php echo $phone; ?>" />
</div>
<div class="form-group">
<label>Youtube video ID <br/><span style="text-decoration: line-through;">https://www.youtube.com/watch?v=</span><strong style="padding:0 5px;border:1px solid gray;">fhgnfyhfth</strong></label>
<input type="text" name="video" class="form-control" minlength="5" maxlength="15" placeholder="Enter Your Youtube video" value="<?php echo $youtube; ?>" />
</div>
<div class="form-group">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000">
<span style="color:red">!</span> Photos:
<input name="userfile[]" required type="file" multiple="multiple" accept="image/*">
</div>
<div id="message"><span style="color:red">!</span> Please verify:</div>
<div id="success">Perfect ✓</div>
<div id="fail"><span style="color:red">!</span> Try again</div>
<p id="question"></p> <input id="ans" type="text">
<p><span style="color:red">!</span> Are you human?<br/> No <input type="checkbox" name="no"> Yes <input type="checkbox" name="yes" required></p>
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>
<div class="form-group inline-label">
<span style="color:red">!</span> <input id="ch1" type="checkbox" name="future" required data-pristine-required-message="You must accept the terms and conditions"/>
<label for="ch1">I accept the terms and conditions</label><br/>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Register" class="btn btn-info" disabled="disabled" /><!--disabled="disabled"-->
</div>
</form>
</div>
<div class="timer" onload="timer(1800)">
<div class="time">
<strong>Time until the page will refresh: <span id="time">Loading...</span></strong>
</div>
</div>
<br/>
<script>
var total;
function getRandom() {
return Math.ceil(Math.random() * 20);
}
function createSum() {
var randomNum1 = getRandom(),
randomNum2 = getRandom();
total = randomNum1 + randomNum2;
jQuery("#question").text(randomNum1 + " + " + randomNum2 + "=");
jQuery("#ans").val('');
checkInput();
}
function checkInput() {
var input = jQuery("#ans").val(),
slideSpeed = 200,
hasInput = !!input,
valid = hasInput && input == total;
jQuery('#message').toggle(!hasInput);
jQuery('input[type=submit]').prop('disabled', !valid);
jQuery('#success').toggle(valid);
jQuery('#fail').toggle(hasInput && !valid);
}
jQuery(document).ready(function() {
//create initial sum
createSum();
// On "reset button" click, generate new random sum
jQuery('input[type=reset]').click(createSum);
// On user input, check value
jQuery("#ans").keyup(checkInput);
//cookie registered
});
</script>
</body>
</html>
If it matters, I am using PHP 7.3, NginX. From my knowledge, same config as when the script used to work.
Also tried this:
Adding the following right after <?php, following the comments
var_dump($_POST["name"]);
var_dump($_POST["age"]);
var_dump($_FILES);
Returns this before submitting the form:
NULL NULL array(0) { }
And this after submitting the form:
string(14) "Johny macaroni" string(2) "22" array(1) { ["userfile"]=> array(5) { ["name"]=> array(1) { [0]=> string(8) "oslo.png" } ["type"]=> array(1) { [0]=> string(9) "image/png" } ["tmp_name"]=> array(1) { [0]=> string(14) "/tmp/phpen1nVm" } ["error"]=> array(1) { [0]=> int(0) } ["size"]=> array(1) { [0]=> int(28358) } } }
In the end, the problem was not related to my script at all. It was the Gmail and Outlook SMTP services that, for some reason, refused to honor the script's SMTP requests; both of them.
So, after switching to a 3rd free SMTP provider, everything started to work as it did before. Solved.
There are quite a few nonsensical things in here. It looks like you've adapted this from a very old example.
The require statements inside the function mean that this will crash the second time you call the function.
You're preprocessing the email address into $email but not using that variable when actually setting the recipient.
You're forging the from address, which is likely to mean your messages will not be delivered.
Sending a copy to the supposed sender means your script is a spam gateway that can be abused to send arbitrary content to arbitrary recipients. This is bad and will be mercilessly exploited by spammers.
Port is an integer, not a string:
$mail->Port = 465;
This will do nothing useful:
$mail->set('X-Priority', '3');
If you want to add a custom header, use addCustomHeader. If you want to set a priority, set the Priority property, which is also an int:
$mail->Priority = 3;
Overall, base your code on the examples provided, particularly the contact form example.
Update
Now that we have a location for the error, we can see that it's in the call to PHPMailer::mb_pathinfo, which passes in $_FILES['userfile']['name'] as the $path parameter, and not in addCC as I had guessed. The HTML form declares this input as an array of file type allowing multiple values:
<input name="userfile[]" required type="file" multiple="multiple" accept="image/*">
This means that $_FILES['userfile']['name'] will be an array, not a string (see the PHP docs), which is the cause of the error.
The fix here is to get the name property of the individual file, not the array of all of them, which is done by adding the array index, so this line:
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
should be:
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'][$ct], PATHINFO_EXTENSION);
This bug was previously present in the example code that this was originally adapted from, though that was fixed 6 months ago.
I am trying to send an email from a contact page. the functionality is working fine, I am able to send mails from the html page but the only issue that I am facing is I am unable to see the Status div(success or failed).
Initially the page was redirecting to php file without any status message. I have added page redirect to the actual mailsend.html using header() in php. Now I want to have a status after the send operation whether mail has sent or not.
Below is the code snippet. Please help. Thanks in advance.
mailSend.html code:
<?php if(!empty($statusMsg)){ ?>
<p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>
<form action="example.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="name" class="form-control" value="" placeholder="Name" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="email" name="email" class="form-control" value="" placeholder="Email address" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="subject" class="form-control" value="" placeholder="Subject" required="">
</div>
<div class="form-group">
<textarea name="message" class="form-control" placeholder="Write your message here" required="" style = 'border :0.5px solid '></textarea>
</div>
<div class="form-group">
<input type="file" name="attachment" class="form-control" style = 'border :0.5px solid; height: auto;'>
</div>
<div class="submit">
<input type="submit" name="submit" class="btn" value="SUBMIT" style= 'float : right;'>
</div>
</form>
example.php code:
<?php
//first we leave this input field blank
$recipient = "";
//if user click the send button
if(isset($_POST['submit'])){
//access user entered data
$recipient = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$sender = "From: xyz#gmail.com";
//if user leave empty field among one of them
if(empty($recipient) || empty($subject) || empty($message)){
?>
<!-- display an alert message if one of them field is empty -->
<div class="alert alert-danger text-center">
<?php echo "All inputs are required!" ?>
</div>
<?php
}else{
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "uploads/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = 'abc#gmail.com';
// Sender
$from = 'xyz#gmail.com';
$fromName = 'example';
// Subject
$emailSubject = 'Contact Request Submitted by '.$recipient;
// Message
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$recipient.'</p>
<p><b>Email:</b> '.$sender.'</p>
<p><b>Subject:</b> '.$subject.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $recipient;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'succdiv';
?>
<!-- display a success message if once mail sent sucessfully -->
<div class="alert alert-success text-center">
<!--<?php echo "Your mail successfully sent to $recipient"?>-->
<!--readfile('submitResume.html');-->
<?php
header('Location: mailSend.html') ;
echo "Your mail successfully sent to $recipient"
?>
</div>
<?php
$recipient = "";
$postData = '';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
?>
<!-- display an alert message if somehow mail can't be sent -->
<div class="alert alert-danger text-center">
<?php echo "Failed while sending your mail!" ?>
</div>
<?php
}
}
}
}
?>
You are sending to a .html page, which does not process PHP code by default, the server just serves it unless specifically configured on the server. Rename the page from mailSend.html to mailSend.php and it should resolve it. Make sure to change your code to send to .php page.
For further reading see here
You would need to pass the message itself or a way for the script to know which message to show. The easiest way would be to pass it via $_GET, by attaching it to the end of the URL you are trying to redirect. Like so:
$target_url = mailSend.php;
$get_data = '?statusMsg=' . urlencode($statusMsg) . '&$msgClass=' . urlencode($msgClass);
header( 'Location: ' . $target_url . $get_data );
Which you can then recover on mailSend.php via the global $_GET variable. Such as:
$statusMsg = urldecode($_GET['statusMsg']);
$msgClass= urldecode($_GET['msgClass']);
There are other ways to get the data from one page to another but that I will leave it up to you to do research. As it is out of scope for a simple answer.
I am trying to set up a contact form which handles multiple file attachments. I am using PHPMailer and built the below script from the PHPMailer example for attaching multiple files.
The below script works great until attachments exceed 100KB. If a file is larger than 100KB, it is skipped when attaching. Only files smaller than 100KB are attached and sent.
I have seen this StackOverflow question which looked promising, but the values in my machine's php.ini file were all set to 32MB or higher.
I am using Mailgun as the SMTP server, and can see in the logs that the attachments that exceed 100KB aren't getting to Mailgun at all so it must have something to do with this script or my PHP environment.
Can anyone help me resolve this?
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$host = 'smtp.mailgun.org';
$username = 'postmaster#domain.com';
$password = 'password';
$email_from = 'from#domain.com';
$email_to = 'to#domain.com';
$send = false;
$subject = "Quote Request from Website";
$name = addslashes(strip_tags($_POST['name']));
$email = addslashes(strip_tags($_POST['email']));
$project_type = addslashes(strip_tags($_POST['project_type']));
$message = addslashes(strip_tags($_POST['message']));
$htmlmessage = <<<MESSAGE
<html>
<head>
<title>$subject</title>
</head>
<body>
<p><strong>Name:</strong> $name</p>
<p><strong>Email:</strong> $email</p>
<p><strong>Project Type:</strong> $project_type</p>
<p><strong>Message:</strong> $message</p>
</body>
</html>
MESSAGE;
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = $username;
$mail->Password = $password;
$mail->Host = $host;
$mail->Port = 587;
$mail->setFrom($email_from, $name);
$mail->addAddress($email_to);
$mail->addReplyTo($email, $name);
// $mail->addCC('cc#example.com');
// $mail->addBCC('bcc#example.com');
// Attach multiple files one by one
$total = count($_FILES['attachments']['tmp_name']);
echo $total;
for ($ct = 0; $ct < $total; $ct++)
{
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['attachments']['name'][$ct]));
$filename = $_FILES['attachments']['name'][$ct];
if (move_uploaded_file($_FILES['attachments']['tmp_name'][$ct], $uploadfile)) {
echo $filename;
$mail->addAttachment($uploadfile, $filename);
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
echo $msg;
}
// $name = $_FILES['attachments']['name'][$ct];
// $path = $_FILES['attachments']['tmp_name'][$ct];
// echo $name . ' - ' . $path . '<br>';
// $mail->addAttachment($path, $name);
}
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $htmlmessage;
// $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
The form:
<form action="contact/quote.php" method="post" id="quote-form" class="validate" role="form" enctype="multipart/form-data">
<label>Name</label>
<input type="text" name="name" id="name" required>
<label>Email</label>
<input type="email" name="email" id="email" required>
<label>Project Type</label>
<select name="project_type" id="project_type" required>
<option value="" selected>Please Select</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<label>Upload Files</label>
<input multiple="multiple" type="file" name="attachments[]" value="">
<label>Message</label>
<textarea name="message" id="message" rows="5" required></textarea>
<button type="submit" id="submit">Submit</button>
</form>
Any help would be much appreciated!
Thanks.
You're missing the MAX_FILE_SIZE option in your form, which won't help, and it defaults to 100k, which exactly matches what you're seeing. See the docs.
The send_file_upload example provided with PHPMailer shows how to set it correctly.
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
I'm trying use honeypot technique for my custom form on wordpress site.
My form look like that.
<form id="form-1"
action="<?php echo get_template_directory_uri(); ?>/mail.php" method="post" class="order__form form">
<p class="form__title">Order and Receive 30% off</p>
<p class="form__text">fill out this form so you can get sale</p>
<input type="text" name="name" class="form__item" placeholder="Your name">
<input type="email" name="email" required class="form__item" placeholder="Email address">
<p class="robotic" id="pot">
<label>If you're human leave this blank:</label>
<input name="robotest" type="text" id="robotest" class="robotest" />
</p>
<input type="submit" value="Send" class="button form__button">
</form>
Input with name robotest for validation on server side.
This is mail.php code:
<?php
$mess = '';
$mess .= '<hr>';
if($_POST['robotest'] != ''){
$error = "You are a gutless robot.";
} else {
if(isset($_POST['name'])) {
$name = substr(htmlspecialchars(trim($_POST['name'])), 0, 100);
$mess .= '<b>Имя отправителя: </b>' . $name . '<br>';
}
if(isset($_POST['email'])) {
if($_POST['email']!=''){
$email = substr(htmlspecialchars(trim($_POST['email'])), 0, 100);
$mess .= '<b>E-mail: </b>' . $email . '<br>';
}
}
}
$mess .= '<b>Заявка пришла со страницы:</b> ' . $_SERVER["HTTP_REFERER"] .'<br>';
$mess .= '<hr>';
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->AddAddress('xxx2xxx.com','');
$mail->IsHTML(true);
$mail->CharSet = "UTF-8";
$mail->Subject = "new";
$mail->From = "new";
$mail->FromName = "new";
$mail->Body = $mess;
if ($mail->Send()) {
header('Location: ../');
} else {
die ('Mailer Error: ' . $mail->ErrorInfo);
}
header("Location: /thanks/");
?>
When I add validation for robotest, this script doesn't work.
You are setting the $error variable but you are not using it anywhere.
If you change the:
$error = "You are a gutless robot.";
To a:
die( "You are a gutless robot." );
You will have what you describe you want to have.
I have PHPmailer library. This is a code which is a password reminder, when you add your email to input, it will send your forgotten password to your email. This code only sends through php mail, but since my host does not allow it, only option would be to use SMTP, right? So this is the php code with form:
<div class="tab-pane fade <?php
if ($tab == 'ForgotPass') {
echo 'active in';
}
?>" id="forgotpass">
<form role="form2" action="index?tab=ForgotPass" method="POST">
<fieldset>
<?php
#$_SESSION['email'] = $_POST['email'];
?>
<hr class="colorgraph">
<div class="form-group">
<input type="email" name="email" maxlength="64" id="email" class="form-control input-lg" placeholder="El. paštas" value="<?= $_SESSION['email'] ?>" required>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="submit" name="forgot" class="btn btn-lg btn-success btn-block" value="send">
</div>
</div>
</fieldset>
</form>
<?php
if (isset($_POST['forgot'])) {
$email = $_POST['email'];
if (empty($email)) {
echo errorbox("Please enter email.");
} else {
$check = mysql_query("SELECT * FROM users WHERE email='$email'");
$row2 = mysql_fetch_assoc($check);
if (mysql_num_rows($check) > 0) {
$query = mysql_query("SELECT * FROM settings");
$row = mysql_fetch_assoc($query);
$subject = 'Forgot Password - ' . $row['title'] . '';
$message = '
<center>
<a href="' . $row['url'] . '" title="Visit ' . $row['url'] . '" target="_blank">
<h1><img src="' . $row['url'] . '' . $row['logo'] . '" title="' . $row['title'] . '"> ' . $row['title'] . '</h1>
</a><br />
<b>Registration details:</b><br />
Username: ' . $row2['username'] . '<b></b><br />
Password: ' . $row2['password'] . '<b></b><br />
</center>
';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'To: ' . $email . ' <' . $email . '>' . "\r\n";
$headers .= 'From: ' . $row['email'] . ' <' . $row['email'] . '>' . "\r\n";
#mail($to, $subject, $message, $headers);
echo okbox("We have just sent you your forgotten data from your account on the entered E-Mail Address");
} else {
echo errorbox("There is no player with such email.");
}
}
}
?>
AND i also have this SMTP configured code which just sends a message to test email and I already tested, it works, it does send the message, now I have to somehow make it so that it would send the password to user email:
<?php
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "mail.website.com";
$mail->SMTPAuth = true;
//$mail->SMTPSecure = "ssl";
$mail->Port = 25;
$mail->Username = "support#website.com";
$mail->Password = "emailpass";
$mail->From = "support#website.com";
$mail->FromName = "Test User";
$mail->AddAddress("emailthatgetsmessage#gmail.com");
//$mail->AddReplyTo("mail#mail.com");
$mail->IsHTML(true);
$mail->Subject = "Test message from server via SMTP Authentication";
$mail->Body = "Test Mail sent via SMTP Authentication";
//$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>