two foreach loops combined for email sending - php

I am trying to take a two text areas with multiple emails, one with the "from" emails, and one with the "to" emails. Combine the emails line by line and send emails out accordingly.
Ex:
"To" list:
mike#gmail.com
nick#hotmail.com
adam#yahoo.com
"From" list:
ashley#gmail.com
brittney#yahoo.com
racheal#hotmail.com
I want a email sent to:
mike#gmail.com from ashley#gmail.com
nick#hotmail.com from brittney#yahoo.com
adam#yahoo.com from racheal#hotmail.com
Any help would be greatly appreciated. Thanks in advanced.
Below is the script I got so far, It sends to multiple emails from one email.
<?php
if (isset($_POST['submit']))
{
// Execute this code if the submit button is pressed.
$raw_email_account = $_POST['email_from'];
$email = $_POST['email_to'];
$sent = "";
$invalid = "";
//Separating each line to be read by foreach
$list = explode("\n",$email);
//Rendering the separeted data from each line
foreach($list AS $data) {
//Separating each line to be read by foreach
$item = explode(":",$data);
$mail_body = '<html><body>email here</body></html>';
$subject = "subject here";
$headers = "From:".$raw_email_account."\r\n";
$headers .= "Content-type: text/html\r\n";
$to = $item[0];
$mail_result = mail($to, $subject, $mail_body, $headers);
if ($mail_result) {
$valid++;
} else {
// write into an error log if the mail function fails
$invalid++;
}
}
}
?>
<html>
<head>
</head>
<body>
<form action="email_sender.php" method="POST">
<div align="center">From Email Accounts: <textarea name="email_from" cols="100" rows="60"></textarea></div><br />
<div align="center">To Email Accounts: <textarea name="email_to" cols="100" rows="60"> </textarea></div><br />
<div align="center"><input type="submit" name="submit"></div>
<br>
Valids: <?php echo $valid;?>
<br>
Invalids: <?php echo $invalid;?>
</body>
</html>

If the array is by default, the indexes will coincide. So you can do something like this.
$toList = array(..);
$fromList = array(...);
foreach($toList as $key => $value) {
$toAddress = $value;
$fromAddress = $fromList[$key];
//..
//.. Go on with you mail function
}

Add logic that provides same count of $email and $raw_email_account arrays before foreach loop.
$list = explode("\n",$email);
$list2 = explode("\n", $raw_email_account);
foreach($list AS $key=>$data) {
...
$headers = "From:".$list2[$key]."\r\n";
...
}

You can use array_combine() to solve that problem easily.
In that case, you first combine the two arrays, and then loop through the resulting array to perform the sending e-mail action.

Related

post my name with array in mail

This is the first project in which I am facing a problem with the mail function. I want to send the option tag value in a mail. At that time I am not getting the of option tag but I am taking name of the select tag in the array because I want to store multiple values in database, that's why I am using an array. Can anyone tell me the solution to this problem?
This is my code:
<select multiple id="00N7F000001F2kO" name="soft_skill[]">
<option value=""selected disabled>soft Skills</option>
<option name="Personality Development" value="Personality Development">personality development</option>
<option name="Communication Skills" value="Communication Skills">communication skills</option>
</select>
And my code with mail function is:
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$soft_skill = $_POST['soft_skill'];
$question = $_POST['question'];
$about_us = $_POST['about_us'];
$to = "kuljeet#mightymente.com";
$subject = "Web Enquiry";
$message = "................";
$header = "From:$email"."\r\n"."CC: kuljeetdhiman06#gmail.com";
if(mail($to, $subject, $message, $header))
{
echo "";
} else {
echo "";
}
}
You can not pass the array directly in mail,
either You should use the implode method and specify any delimiter you wish to use. If you will select multiple option then by using implode you will get result like Personality Development , Communication Skills
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$soft_skill= implode("," , $_POST['soft_skill']);
$question=$_POST['question'];
$about_us=$_POST['about_us'];
$to="kuljeet#mightymente.com";
$subject="Web Enquiry";
$message="................";
$header="From:$email"."\r\n"."CC: kuljeetdhiman06#gmail.com";
if(mail($to, $subject, $message, $header)) {
echo "";
} else{
echo "";
}
}
And i saw you message variable is like
$message="................";
Here you need to concate all the values using .= like,
$message = "Name : ".$name."\n\n";
$message.= "Soft Skils : ".$soft_skill."\n\n";
$message.= "Question : ".$question."\n\n";
$message.= "About Us : ".$about_us."\n\n";
Hope this will be helpful to you.
You can use
$temp_softSkill=implode(",",$_POST['soft_skill']);
Because it is an array so you have to use indexes of soft skill array like $_POST['soft_skill'][0] which one u want

after clicking submit on a contact form, how do i stay on the same page in wordpress?

So I created a custom contact form in WordPress, using PHP. The form sends, and I am receiving emails. The problem I'm having is that once you hit submit, it goes to a post page, and doesn't stay on the original page.
I've tried using a session and header location (didn't work)
I also tried putting this in my action"<?php echo $_SERVER['PHP_SELF']; ?>", doesn't work either. (mail just doesn't send it and sends me to 404 page.
So I'm a little stuck, as to fix this problem. Normally I would have no problems if this was a static web page, but because I'm using WordPress, this task seems to be more troublesome.
Here is a link to the website http://www.indianpointresort.ca/
Here is the php validation:
<?php
/*session_start();
if(!isset($_SESSION['afaisfjisjfijfjiwaefjawsefijef'])){
$url = 'http://www.indianpointresort.ca/';
header("Location:home.php?url=$url");
}*/
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
echo "$name | $email | $phone | $subject | $message";
if(isset($_POST['submit'])){
$boolValidationOK = 1;
$strValidationMessage = "";
//validate first name
//validate last name
if(strlen($name)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper first and last name </br>";
}
//email validation:
$emailValidate = validate_email( $email );// calls the function below to validate the email addy
if(!$emailValidate ){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in proper email address </br>";
}
//validate phone
$phone = checkPhoneNumber($phone);
if(!$phone){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill proper phone number </br>";
}
//validate subject
if(strlen($subject)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper subject description </br>";
}
//validate description
if(strlen($message)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper message </br>";
}
if($boolValidationOK == 1){
//$strValidationMessage = "SUCCESS";
//MAIL SECURITY !!!!!!!
// WE MUST VALIDATE AGAINST EMAIL INJECTIONS; THE SPAMMERS BEST WEAPON
$badStrings = array("Content-Type:",
"MIME-Version:",
"Content-Transfer-Encoding:",
"bcc:",
"cc:");
foreach($_POST as $k => $v){// change to $_POST if your form was method="post"
foreach($badStrings as $v2){
if(strpos($v, $v2) !== false){
// In case of spam, all actions taken here
//header("HTTP/1.0 403 Forbidden");
echo "<script>document.location =\"http://www.bermuda-triangle.org/\" </script>";
exit; // stop all further PHP scripting, so mail will not be sent.
}
}
}
$ip = $_SERVER['REMOTE_ADDR'];
//echo $ip;
/* Spammer List: IP's that have spammed you before ***********/
$spams = array (
"static.16.86.46.78.clients.your-server.de",
"87.101.244.8",
"144.229.34.5",
"89.248.168.70",
"reserve.cableplus.com.cn",
"94.102.60.182",
"194.8.75.145",
"194.8.75.50",
"194.8.75.62",
"194.170.32.252"
//"S0106004005289027.ed.shawcable.net" Phil's IP as test
); // array of evil spammers
foreach ($spams as $site) {// Redirect known spammers
$pattern = "/$site/i";
if (preg_match ($pattern, $ip)) {
// whatever you want to do for the spammer
echo "logging spam activity..";
exit();
}
}
$to = "";
//$subject = " Indian Point";
// compose headers
$headers = "From: Indian Point Resort.\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "X-Mailer: PHP/".phpversion();
$message = wordwrap($message, 70);
// send email
mail($to, $subject, $message, $headers);
}
}//end of submit
//validate phone number
function checkPhoneNumber($number){
$number = str_replace("-", "", $number);
$number = str_replace(".", "", $number);
$number = str_replace(" ", "", $number);
$number = str_replace(",", "", $number);
$number = str_replace("(", "", $number);
$number = str_replace(")", "", $number);
if((strlen($number) != 10) || (!is_numeric($number))){
return false;
}else{
return $number;
}
}
//email validation
function validate_email( $senderemail ){ // this is a function; it receives info and returns a value.
$email = trim( $senderemail ); # removes whitespace
if(!empty($email) ):
// validate email address syntax
if( preg_match('/^[a-z0-9\_\.]+#[a-z0-9\-]+\.[a-z]+\.?[a-z]{1,4}$/i', $email, $match) ):
return strtolower($match[0]); # valid!
endif;
endif;
return false; # NOT valid!
}
?>
Here is the form:
<div id="msgForm" class=" msgForm five columns">
<h4>Questions?</h4>
<h5>Send us a message!</h5>
<form id="contactForm" name="contactForm" method="post" action="<?php the_permalink(); ?>">
<p><input type="text" name="name" value="<?php echo $name; ?>" placeholder="name*"/></p>
<p><input type="email" name="email" placeholder="E-mail*"/></p>
<p><input type="text" name="phone" placeholder="Phone #*"/></p>
<p><input type="text" name="subject" placeholder="subject*"/></p>
<p><textarea name="message" placeholder="Message*"></textarea></p>
<p><input type="submit" name="submit" placeholder="Submit"/></p>
<div class="error">
<?php
if($strValidationMessage){
echo $strValidationMessage;
}
?>
</div>
</form>
</div><!--end of form-->
Well, to start off I would remove that gmail account from your info (just to be safe).
Secondly I would advise you to use the sendmail scripts provided by Wordpress.
There are plugins like gravityforms which allow you to make a form and decide all these options without making a static form, nor a new template file for that matter.
You can only change to which page the form will redirect after the refresh (the action will decide that)
If you want it to stay on the same page you can put the page itself in the action and on top put an if statement like
if(isset($_POST['submit'])){
//validation, sendmail, and possibly errors here
}
else{
//show the form
}
anyway, a refreshing webform is as standard as it gets. It's just how it submits things. The only way you could prevent a page is by using jquery or javascript like so: (give your submit an id)
$('#submit').on("click", function(e){
//this prevents any submit functionality (like refresh)
e.preventDefault();
//custom code to get values here and put them in the sendmail function like so:
var message = $('$message').text();
}
Try ajax form submission. And add the insert query in a separate file.

PHP Page is not Sending Email

I have a page that has a form for the user to input their email into. Once the form is submitted the email gets checked in my MSSQL table and if it exists in one of the table's rows it will send an email to the user's email. Right now, I correctly put in an existing email and the email is never received. I am trying to make this so that if the user forgets their password, it will retrieve the password from the correct row and send that password to the user's email.
Here is my PHP page code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$conn=mssql_connect('gdm','dr','Rd1!');
mssql_select_db('Gdr',$conn);
if (isset($_POST['forgotpass'])) {
$conn=mssql_connect('gdom','GBdr','d1!');
mssql_select_db('Gdr',$conn);
if (!get_magic_quotes_gpc()) {
$_POST['email'] = addslashes($_POST['email']);
}
$email = $_POST['email'];
$querye = "SELECT password FROM staffportal WHERE email = '".$_POST['email']."'";
$check = mssql_query($querye, $conn);
$check2 = mssql_num_rows($check);
echo "".$check2."";
//if the email doesn't exist it gives an error
if ($check2 != 0) {
print"<p>Thank you, dsa we will get back to you.</p>";
print"<p>Today's date isdsa.</p>";
ob_start();
$tae = "".$_POST['email']."";
echo "".$tae."";
$out2 = ob_get_contents();
ob_end_clean();
var_dump($out2);
var_dump($out2);
$to = "".$out2."";
echo "Emailing to: ".$to."";
$subject = "Financing fordsac ";
$body = "dsdasd \n\n";
$headers = "From: info#gbmtd.ca";
mail($to, $subject, $body, $headers);
} else {
echo "Sorry, the email ".$email." is incorrect.";
} } else {
?>
<form method="POST" action="<?php $_PHP_SELF ?>">
Email:<br />
<input type="text" name="email" id="email"/>
<br /><br />
<input type="submit" id="forgotpass" value="Change Password" name="forgotpass"/>
</form>
<?php } ?>
</body>
</html>
This gets displayed on my page after I hit submit:
1
Thank you, dsa we will get back to you.
Today's date isdsa.
string(22) "kelseynealon#gmail.com" string(22) "kelseynealon#gmail.com" Emailing to: kelseynealon#gmail.com
All help is greatly appreciated. Thank you for any help.
I've had mixed luck with the PHP mail function. You can take a gander at the PHP mail function page http://www.php.net/manual/en/function.mail.php to look for clues. Personally I use PHP SwiftMailer (http://swiftmailer.org/) for any email sending from PHP applications and it works really well.
Here's a generic function I have for using it:
/*
Starting code for sending email via this function:
list($email_logger, $email_mailer) = email_interface();
$message = Swift_Message::newInstance()
->setFrom(array('from#domain.ext' => 'John Doe'))
->setTo(array('to#domain.ext' => 'Jane Doe'))
->setSubject('<SUBJECT>')
->setBody('<BODY>');
$email_mailer->send($message);
*/
// Returns PHP SwiftMailer mailer and logger email interfaces
function email_interface()
{
// Mail configuration
$global_email_config = array(
//'relay_encryption' => 'ssl',
//'relay_host' => 'relayhost.domain.ext',
//'relay_port' => '465',
// 'relay_user' => '<ADDR>',
// 'relay_pass' => '<PASS>',
'smtp_sender' => array(
'sender#domain.ext' => 'Sender Name'
)
);
if (isset($global_email_config['relay_host'])) {
$transport = Swift_SmtpTransport::newInstance();
$transport->setHost($global_email_config['relay_host']);
if (isset($global_email_config['relay_port'])) {
$transport->setPort($global_email_config['relay_port']);
}
if (isset($global_email_config['relay_encryption'])) {
$transport->setEncryption($global_email_config['relay_encryption']);
}
if (isset($global_email_config['relay_user'])) {
$transport->setUsername($global_email_config['relay_user']);
$transport->setPassword($global_email_config['relay_pass']);
}
} else {
$transport = Swift_SendmailTransport::newInstance();
}
$mailer = Swift_Mailer::newInstance($transport);
$logger = new Swift_Plugins_Loggers_ArrayLogger();
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
return array(
$logger,
$mailer
);
}

PHP form mail to work with invisible form field to filter bots

I read this post: What is a good invisible captcha? about using a hidden field in a web form to stop basic bots from pelting your website with spam mail via your web sites form mail. I'm currently using a php script to process my form mail. I built the script by following a 'bullet proff web form' tutorial I found. It looks like this:
<?php
// Pick up the form data and assign it to variables
$name = $_POST['name'];
$email = $_POST['email'];
$topic = $_POST['topic'];
$comments = $_POST['comments'];
// Build the email (replace the address in the $to section with your own)
$to = 'hello#cipherbunny.com';
$subject = "New message: $topic";
$message = "$name said: $comments";
$headers = "From: $email";
// Data cleaning function
function clean_data($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
$string = strip_tags($string);
return mysql_real_escape_string($string);
}
// Mail header removal
function remove_headers($string) {
$headers = array(
"/to\:/i",
"/from\:/i",
"/bcc\:/i",
"/cc\:/i",
"/Content\-Transfer\-Encoding\:/i",
"/Content\-Type\:/i",
"/Mime\-Version\:/i"
);
$string = preg_replace($headers, '', $string);
return strip_tags($string);
}
// Pick up the cleaned form data
$name = remove_headers($_POST['name']);
$email = remove_headers($_POST['email']);
$topic = remove_headers($_POST['topic']);
$comments = remove_headers($_POST['comments']);
// Send the mail using PHPs mail() function
mail($to, $subject, $message, $headers);
// Redirect
header("Location: http://foobar/success.html");
I'd like to modify this script so that if a hidden field with the identifier 'other_email' was filled in then the form email wouldn't get sent. I'm guess it's as straight forward as wrapping the above code in an if statement to check if the field is complete. I've tried adding this under the "//Pick up the form data and assign it to variables" code:
$testBot = $_POST['other_email'];
then writing:
if(other_email == "") //If other_email form section is blank then...
{
run all the code above inserted here;
}
else
{
Don't know what I should put here to stop it posting, yet still show the success form so
the spam bot don't know
}
any help much appreciated. I have to say I don't really have a lot of php knowledge, I'm just starting to learn about it and thought form mail would be a good start.
How do I make this work in PhP?
if(other_email == "") //If other_email form section is blank then...
{
run all the code above inserted here;
}
else
{
header("Location: http://foobar/success.html");
}
keeping it very simple, it will work for you..
actually, it will
not submit / mail you anything...so NO SPAM
a simple bot will take it as it did it...
if you can use php on success page, then set a session variable (to make bot think it did its job, something like email_sent=true or success=true) and use that variable in success page, you will do it in else case where bot submitted the form..
Do you mean send message with fields?
Try this:
<?php
// Pick up the form data and assign it to variables
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$topic = $_REQUEST['topic'];
$comments = $_REQUEST['comments'];
// Build the email (replace the address in the $to section with your own)
if($name !== null && $email !== null && $topic !== null && $comments !== null){
$to = 'hello#cipherbunny.com';
$subject = "New message: $topic";
$message = "$name said: $comments";
$headers = "From: $email";
// Data cleaning function
function clean_data($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
$string = strip_tags($string);
return mysql_real_escape_string($string);
}
// Mail header removal
function remove_headers($string) {
$headers = array(
"/to\:/i",
"/from\:/i",
"/bcc\:/i",
"/cc\:/i",
"/Content\-Transfer\-Encoding\:/i",
"/Content\-Type\:/i",
"/Mime\-Version\:/i"
);
$string = preg_replace($headers, '', $string);
return strip_tags($string);
}
// Pick up the cleaned form data
$name = remove_headers($_POST['name']);
$email = remove_headers($_POST['email']);
$topic = remove_headers($_POST['topic']);
$comments = remove_headers($_POST['comments']);
// Send the mail using PHPs mail() function
mail($to, $subject, $message, $headers);
// Redirect
header("Location: http://foobar/success.html");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=shift_jis" />
<title>Send</title>
</head>
<body>
<form action="#" method="POST">
Name : <input type="text" name="name" /><br />
Email : <input type="text" name="email" /><br />
Topic : <input type="text" name="topic" /><br />
Comments : <textarea name="comments"></textarea><br />
<input type="submit" value="Send" />
</form>
</body>
</html>

storing variables within foreach loop

Hi I currently have some PHP code which will put previously selected timeslots from checkboxes on a previous page into my database, but I'm not sure how to store each one in a variable before I do this, so that I can use them to list the appointment slot's in my e-mail function
At the moment when I try to insert '$key' to my e-mail function it only retains the last selected value...
My code on the first page reads:
<?php
for ($i=0;$i<=31;$i++){ while ($myrow = mysql_fetch_row($result)) {
printf("<tr><td>%s</td><td>%s</td></tr>\n",
$myrow[0]);
}
echo "<td><input type='checkbox' name='$displayTime2' onclick='KeepCount()'></td>";
echo "<td>$pagetime</td>"; ?>
My code at the moment is as follows:
<?php
foreach ($_POST as $key=>$value)
{
echo $key; // show times selected on previous page
mysql_query("INSERT INTO appointment(Patient_ID, Appointment_Date, Appointment_Time
, Practice_ID, Appointment_ID)
VALUES('$patid','$insertdate','$key','$pracid','$apptype')");
}
?>
my mail function is as follows:
$to = "$pemail";
$subject = "Talking Teeth Check Up Booking Confrmation";
$message = "Hello! This e-mail is to confirm your ".$appname." appointment has been
booked for ".$insertdate. " at ".$key." at the ".$pracname." practice";
$from = "talkingteethdentists#talkingteeth.co.uk";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
Although the comments above are right, let me help you out.
First off, you need to figure out which checkboxes were selected, so do some IF statements to figure that out on each of these inside of your foreach loop.
Try something like this:
<?php
$savedData = array();
foreach ($_POST as $key=>$value){
$key = mysql_real_escape_string($key);
echo($key. "<br>"); // show times selected on previous page
mysql_query("INSERT INTO appointment(Patient_ID, Appointment_Date, Appointment_Time
, Practice_ID, Appointment_ID)
VALUES('$patid','$insertdate','$key','$pracid','$apptype')");
//To save the variables for later:
$savedData[] = $key;
}
?>
And now you can access all of our KEYs with $savedData[0] .... $savedData[1] ... $savedData[2] .... etc....
So your email function might look like:
foreach($savedData as $time){
$to = "$pemail";
$subject = "Talking Teeth Check Up Booking Confirmation"; //mis-spelled confirmation =)
$message = "Hello! This e-mail is to confirm your ".$appname." appointment has been
booked for ".$insertdate. " at ".$time." at the ".$pracname." practice";
$from = "talkingteethdentists#talkingteeth.co.uk";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
}
So this will send out an email for each piece inside $savedData - if that truly is the intent.

Categories