php mail two forms one button

Discuss coding issues, and scripts related to PHP and MySQL.
User avatar
JanMolendijk
Posts:282
Location:Holland Rotterdam

php mail two forms one button

Hello I found a mail script with add file`s function
only I would like to build a seccond mail-function
in it so the sender gets a copy from his comment.

Code: Select all

<?php 
if(isset($_POST['submit'])){
    $to = "jan-molendijk@live.nl"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>

Code: Select all

<form id="frmEnquiry" action="" method="post" enctype='multipart/form-data'>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
    <div id="mail-status"></div>
    <div>
        <input
            type="text" name="userName" id="userName"
            class="demoInputBox" placeholder="Name">
    </div>
    <div>
        <input type="text" name="userEmail" id="userEmail"
            class="demoInputBox" placeholder="Email">
    </div>
    <div>
        <input type="text" name="subject" id="subject"
            class="demoInputBox" placeholder="Subject">
    </div>
    <div>
        <textarea name="content" id="content" class="demoInputBox"
            cols="60" rows="6" placeholder="Content"
> (keep on-top) Reference-ID: <?php echo $_GET['reference-id'] ?>)

</textarea>
 </div>
    <div>
        <label>Attachment</label><br /> <input type="file"
            name="attachment[]" class="demoInputBox" multiple="multiple">
    </div>
    <div><br>
<h2>save your Reference-ID: <?php echo $_GET['reference-id'] ?></h2><br>
        <input type="submit" value="Send" class="btnAction" />
<br><br>
    </div>
</form></form>
This above is not correctly working one function is only working

Hope you can help me ????

Admin Posts:805
If you use a single submit button, add the input fields into a single form element.
I tested the following script and it was worked.
Anyway, some email servers put the emal into Spam folder, or the email is received after a long time.
Also, it depends of the configuration of the mail server that sends data.

HTML:

Code: Select all

<form action='send_mail.php' method='post' enctype='multipart/form-data'>
First Name: <input type='text' name='first_name'><br>
Last Name: <input type='text' name='last_name'><br>
Email: <input type='text' name='email'><br>
Message:<br><textarea rows='5' name='message' cols='30'></textarea><br>
<div>
  <label>Attachment</label><br> <input type='file' name='attachment[]' class='demoInputBox' multiple='multiple'>
</div>
<div><br>
  <h2>save your Reference-ID: <?php echo $_GET['reference-id'] ?></h2><br>
  <input type='submit' value='Send' name='submit' class='btnAction' />
  <br><br>
</div>
</form>
PHP (send_mail.php):

Code: Select all

<?php
header('Content-type: text/html; charset=utf-8');

function mail_att($to, $from, $sub, $msg, $attach) {
 $headers = "From: ".$from;

 $rand_hash = md5(time());
 $mime_boundary = "==Multipart_Boundary_x".$rand_hash."x";

  $headers = "From: User <{$from}>\r\n".
  "Reply-To: ".$to."\r\n".
  "Cc: ".$from."\r\n".
  "MIME-Version: 1.0\n".
  "Content-Type: multipart/mixed;\n".
  ' boundary="'.$mime_boundary.'"';

 $body = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=ISO-8859-1\n" . 
"Content-Transfer-Encoding: 8bit\n\n" . $msg . "\n\n";

 if (count($attach)>=1) {
	for($i=0; $i<count($attach); $i++) {
	 if ($file = fopen($attach[$i][0],'rb')) {
		$data = fread($file, filesize($attach[$i][0]));
		fclose($file);
	 }

	 $data = chunk_split(base64_encode($data));

	 $body .= '--'.$mime_boundary."\n".
		'Content-Type: '.$attach[$i][2].";\n".
		' name="'.$attach[$i][1]."\"\n".
		"Content-Transfer-Encoding: base64\n\n".$data ."\n\n";
	}
  $body .='--'.$mime_boundary."\n";
 }

 if(mail($to, $sub, $body, $headers)) return true;
 else return false;
}

if(isset($_POST['submit'])){
  $to = 'jan-molendijk@live.nl';
  $from = strip_tags($_POST['email']);
  $subj = 'Form submission';
  $msg = $_POST['message'];
  $first_name = strip_tags($_POST['first_name']);
  $last_name = strip_tags($_POST['last_name']);
  $subject2 = 'Copy of your form submission';
  $message2 = 'Here is a copy of your message '. $first_name ."\n\n". $msg;
  $headers2 = "From: Admin <{$to}>\r\n".
  "Reply-To: ".$to."\r\n".
  "MIME-Version: 1.0\r\n".
  "Content-type: text/html; charset=UTF-8";

  if($_POST && isset($_FILES['attachment'])){
    $attach = array();
    $att = $_FILES['attachment'];
    $file_count = count($att['name']);
    for($i=0; $i<$file_count; $i++){
      $attach[] = array($att['tmp_name'][$i], $att['name'][$i], 'application/octet-stream');
    }
  }


  $go_mail = mail_att($to, $from, $subj, $msg, $attach);
  if($go_mail){
    echo 'Mail 1 sent: '.$from.'</br>';
    sleep(2);
    if(mail($from,$subject2,$message2,$headers2)){ // sends a copy of the message to the sender
      echo 'Mail Sent. Thank you '. $first_name .', we will contact you shortly. Admn: '. $to;
    }
    else echo 'Unable to send copy mail';
  }
  else echo 'Error: Unable to send the email';
}
else echo 'Not form submit';

JanMolendijk Posts:282
I tried this allready I did not placed the other part from the script.
When I try both forms in one only one form is sended

& did not added it correctly (sorry sorry for this)

2 forms in this code 1 mailfunction

Code: Select all

<form name="contactform" method="post" action="">

<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
    <div id="mail-status"></div>
    <div>


<form id="frmEnquiry" action="" method="post" enctype='multipart/form-data'>

        <input type="text" name="userName" id="userName"
            class="demoInputBox" placeholder="Name">
    </div>
    <div>
        <input type="text" name="userEmail" id="userEmail"
            class="demoInputBox" placeholder="Email">
    </div>
    <div>
        <input type="text" name="subject" id="subject"
            class="demoInputBox" placeholder="Subject">
    </div>
    <div>
        <textarea name="content" id="content" class="demoInputBox"
            cols="60" rows="6" placeholder="Content"
> (keep on-top) Reference-ID: <?php echo $_GET['reference-id'] ?>)

</textarea>
 </div>
    <div>
        <label>Attachment</label><br /> <input type="file"
            name="attachment[]" class="demoInputBox" multiple="multiple">
    </div>
    <div><br>
<h2>save your Reference-ID: <?php echo $_GET['reference-id'] ?></h2><br>
        <input type="submit" value="Send" class="btnAction" />
<br><br>
    </div>
</form></form>




<?php
if(isset($_POST['email'])) {
 
    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "jan-molendijk@live.nl";
    $email_subject = "Your email subject line";
 
    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
    }
 
 
    // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');       
    }
 
     
 
    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required
 
    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
 
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
  }
 
    $string_exp = "/^[A-Za-z .'-]+$/";
 
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.<br />';
  }
 
  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
  }
 
  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.<br />';
  }
 
  if(strlen($error_message) > 0) {
    died($error_message);
  }
 
    $email_message = "Form details below.\n\n";
 
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
 
     
 
    $email_message .= "First Name: ".clean_string($first_name)."\n";
    $email_message .= "Last Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Comments: ".clean_string($comments)."\n";
 
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);  
?>
 
<!-- include your own success html here -->
 
Thank you for contacting us. We will be in touch with you very soon.
 
<?php
 
}
?>
seccond comment other codes are posted excuse

JanMolendijk Posts:282
Sorry for the mash Coursesweb (above comment is first part)

Script part in this code

Code: Select all

<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function (e){
$("#frmEnquiry").on('submit',(function(e){
	e.preventDefault();
	$('#loader-icon').show();
	var valid;	
	valid = validateContact();
	if(valid) {
		$.ajax({
		url: "mail-send.php",
		type: "POST",
		data:  new FormData(this),
		contentType: false,
		cache: false,
		processData:false,
		success: function(data){
		$("#mail-status").html(data);
		$('#loader-icon').hide();
		},
		error: function(){} 	        
		
		});
	}
}));

function validateContact() {
	var valid = true;	
	$(".demoInputBox").css('background-color','');
	$(".info").html('');
	$("#userName").removeClass("invalid");
	$("#userEmail").removeClass("invalid");
	$("#subject").removeClass("invalid");
	$("#content").removeClass("invalid");
	
	if(!$("#userName").val()) {
		$("#userName").addClass("invalid");
        $("#userName").attr("title","Required");
        valid = false;
	}
    if(!$("#userEmail").val()) {
        $("#userEmail").addClass("invalid");
        $("#userEmail").attr("title","Required");
        valid = false;
    }
    if(!$("#userEmail").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
        $("#userEmail").addClass("invalid");
        $("#userEmail").attr("title","Invalid Email");
        valid = false;
    }
	if(!$("#subject").val()) {
		$("#subject").addClass("invalid");
        $("#subject").attr("title","Required");
		valid = false;
	}
	if(!$("#content").val()) {
		$("#content").addClass("invalid");
        $("#content").attr("title","Required");
		valid = false;
	}
	
	return valid;
}

});
</script>


This under is my other part from send email

the script is alone-stand part

Code: Select all

<?php
require('phpmailer/class.phpmailer.php');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Port     = 465;  
$mail->Username = "YOUR USER_NAME";
$mail->Password = "YOUR PASSWORD";
$mail->Host     = "YOUR HOST";
$mail->Mailer   = "smtp.kpnmail.nl";
$mail->SetFrom($_POST["userEmail"], $_POST["userName"]);
$mail->AddReplyTo($_POST["userEmail"], $_POST["userName"]);
$mail->AddAddress("jan-molendijk@live.nl");	
$mail->Subject = $_POST["subject"];
$mail->WordWrap   = 80;
$mail->MsgHTML($_POST["content"]);

foreach ($_FILES["attachment"]["name"] as $k => $v) {
    $mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}

$mail->IsHTML(true);

if(!$mail->Send()) {
	echo "<p class='error'>Problem in Sending Mail.</p>";
} else {
	echo "<script type='text/javascript'>   
    function Redirect() 
    {  
        window.location='http://145.53.93.209/Molendijk/home/'; 
    } 
    document.write('E-mail send succesfully'); 
    setTimeout('Redirect()', 3000);   
</script>";
}	
?>


Admin Posts:805
Sorry, it's a mixes of to much code with ajax, and phpmailer.
I can't involve more in that because it's not so coherent for me.

JanMolendijk Posts:282
Still mutch thanks for your support like allway`s