Mail function on Live Server is Not sending Mails - php

I have a website and have enabled to send mail using the By default mail function of php
My code is this
I have tested it from other posts also.. and for me it is correct.. but it is still not sending the message. Please tell me.. where is the problem
<?php
include_once './config.php';
$con=mysqli_connect(mysql_host,mysql_user,mysql_password,mysql_database);
$Roll = $_REQUEST['UserName'];
ini_set('display_errors',1);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$confirmCode = md5(uniqid(rand()));
$tbl_name1 = "temp_forgot_acc";
$orderCheck = "DELETE FROM $tbl_name1 WHERE EmailId = '$Roll'";
mysqli_query($con,$orderCheck);
$order = "INSERT INTO $tbl_name1 (EmailId,confirm_code) VALUES ('$Roll','$confirmCode')";
$result = mysqli_query($con,$order);
//if($result)
// {
// ---------------- SEND MAIL FORM ----------------
// send e-mail to ...
$to=$Roll;
// Your subject
$subject="Your Forgot Pass link here";
// From
$header = 'From: Admin <admin#test.com>' . "\r\n";
// Your message
$message="Your Comfirmation link \r\n";
$message.="http://www.test.com/test.html?passkey=$confirmCode&Email=$Roll";
// send email
mail($to,$subject,$message,$header);
// }
echo '{"data":[';
echo "{" . '"Finish":'.'"YES"}';
echo ']}';
}
mysqli_close($con);
exit();
?>
I am able to insert it in the database... but it is not sending the maill.

Try code something like this in your application:
$from = "sender id" // sender must be valid
$subject = "subject";
$message = 'mail from'.$from.'sender';
$to = "receiver id";
// send mail
$headers = 'From: <test#test.com>' . "\n";
$headers .= "MIME-Version: 1.0\n" ;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
mail($to,$subject,$message,$headers);
and check what you have in $to value..email id must be correct.

Related

php sendmail form fails, worked for years

I have a php contact form which has been working reliably for several years up until Jan 2022. It uses a Google reCaptcha. Apparently it fails at the mailcheck part which is near the end and prints out the "MAIL Sending Failed" message
<?php
//dont need these
error_reporting(E_ALL);
ini_set('display_errors', 1);
// check form is submitted
if ( isset($_POST['form_submit']) ) {
// get values
$error = ''; //error variable
$visitor_name = $_POST['name'];
$visitor_email = $_POST['email'];
$visitor_message = $_POST['message'];
$captcha = $_POST['g-recaptcha-response'];
//required values
if ( empty($visitor_name) || empty($visitor_email) ) {
$error = "<h3>Name and Email are required. END.</h3>";
}
//required captcha
if ( empty($captcha) ) {
$error = "<h3>Please check the the captcha form. END.</h3>";
}
// if no errors
if( empty($error) ){
$secretKey = " *** hidden *** ";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' .
urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
// should return JSON with success as true
if ($responseKeys["success"]) {
echo '<h3>Captcha Success. Writing Mail...</h3>';
// write mail
$to = " *** my user email ***.com";
$email_subject = "C&H form v2c inquiry";
// To send HTML mail, the Content-type header must be set
// If the From header is not set, then Luxsci servers reject
// $headers = "";
$headers = "From: *** my email ***.com \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
$headers .= "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers .= "X-Mailer: PHP/".phpversion();
$email_body = "message from " . $visitor_name . "<br>" .
"sender's email: " . $visitor_email . "<br>" .
"here is the message: " . $visitor_message;
// compose headers
//Send the mail
$mail_check = mail($to, $email_subject, $email_body, $headers);
if ($mail_check) {
echo "<h5>Mail sending successful. Redirecting... </h5>";
echo '<script> window.location.href = "thank_you_CG.html"; </script>';
} else {
echo "<h5>MAIL sending failed.</h5><br<br>
<h3> This is the failure message it sends out HERE </h3>";
}
} else { // if response not success
echo '<h3>reCaptcha verification failed!</h3>';
echo "Response from reCaptcha: <br>";
print_r($responseKeys);
}
} else { //if errors
echo $error;
exit;
}
}
I can also add the html but there seems to be no problem with that. As mentioned this php form was working fine for years then stopped. I've heard that the Google recaptcha uses a smaller string now?

How to run mail function only once?

I want to send mail (only once) using php when $cstt == 10. I want to prevent sending mail on every time I refresh the page. here is my code
if ($cstt == 10) {
echo "Great";
// SENDING EMAIL
$to = "user#example.com";
$subject = "$tracking_id_user is in transit.";
$message =' Hi user, Simple html message. Best Regards!';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Company <info#company.com>' . "\r\n";
if(mail($to,$subject,$message,$headers)){
echo "mail send";
}else{
echo "email not sent";
}
}
I did the following tasks to achieve the result.
Created a Table mail_record.
added id and mail_sent columns.
after creating the table, wrote the following code.
Connectin to database
$conn = new mysqli('localhost', 'user_id', 'password', 'databasename');
Accessing the data
$sql = "SELECT * FROM mail_record";
$query = $conn->query($sql);
$row = $query->fetch_assoc();
Accessing database to get mail_sent record.
// GETTING MAIL SENT / NOT RECORD (BLANK = NOT SENT & yes10 = Sent)
$mail_status = $row(['mail_sent']);
// CREATING THE CONDITION
if($cstt == 10 and $mail_status == ''){
// SENDING EMAIL if $cstt = 10 & email is not sent (blank)
$to = "admin#example.com, user#example.com";
$subject = "email subject";
$message ='Hi user, email text';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Web admin <admin#example.com>' . "\r\n";
if(mail($to,$subject,$message,$headers)){
// ADDING The RECORD THAT EMAIL HAS BEEN SENT FOR ($CSTT == 10)
$sql = "INSERT INTO `mail_record ` (`mail_sent`) VALUES ('yes10')";
if ($conn->query($sql) === TRUE) {
echo "Email sent and record added successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
by adding a if condition / logic we can write a code to execute mail send action only once.
now if you refresh the page the first if condition will give result FALSE because $cstt == 10 TRUE but $mail_status == '' FALSE.
using this method you can be very sure that the mail will be sent only once. no matter how many times page is being refreshed.

Sending mass emails using PHP script, MySQL database

I want to send mass emails using PHP mail function. Email addresses are stored in MySQL database. There are nearly 30k email addresses. I am sending one email at a time.
60 emails are sent properly & the next all emails are skipped. I am using godaddy host to send emails. Following is code I am using
<?php
$con1=mysqli_connect("subscibe","subscibe","pw","subscibe");
$subject = $_POST['subject'];
$message = $_POST['message'];
$getusers = mysql_query("SELECT * FROM subscibe.emaillist");
$email_from = "email#gmail.com";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
while($result = mysql_fetch_array($getusers)) {
$emailaddress = $result['Emailaddresses'];
mail($emailaddress,$subject,$message,$headers);
//Add email address to temp table
$sqlq="INSERT INTO subscibe.temp VALUES ('$emailaddress')";
if (!mysqli_query($con1,$sqlq)) {
die('Error: ' . mysqli_error($con1));
}
}
echo "Emails are sent"
?>
you may want to use a foreach loop which would send the email to each record in your DB.
Something like:
$getusers = mysql_query("SELECT * FROM subscibe.emaillist");
foreach ($getusers as $maillist) {
$mail->to($mailist['email_address']);
$mail->send()
<?php
$con = mysql_connect("localhost","dbuser","dbpass"); // replace dbuser, dbpass with your db user and password
mysql_select_db("dbname", $con); // replace dbname with your database name
/*
To use this script database table must have three fields named sno, email and sub_status
*/
$query = "select sno, email from dbtable where sub_status = 'SUBSCRIBED'";
$result = mysql_query($query, $con);
$emails = array();
$sno = array();
while($row=mysql_fetch_assoc($result))
{
$sno[] = $row['sno']; // this will be used to unsubscribe the user
$emails[]=$row['email']; // email id of user
}
/* you can also get email id data from CSV using below code */
//$file = file_get_contents("travel_database.csv");
//$emails = explode(",",$file);
/* count.txt is used to store current email sent number/count */
$count = file_get_contents("count.txt");
for($i=$count;$i<count($emails);$i++)
{
$to = $emails[$i];
// subject
$subject = 'Set Your Title Here';
// message
$message = file_get_contents("sample.html"); // this will get the HTML sample template sample.html
$message .= '<p>Please click here to unsubscribe.</p>
</body>
</html>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
//$headers .= "To: $to" . "\r\n";
$headers .= 'From: Name <info#yourdomain.com>' . "\r\n";
//$headers .= 'Cc: sendcc#yourdomain.com' . "\r\n";
//$headers .= 'Bcc: sendbcc#yourdomain.com' . "\r\n";
// Mail it
if(mail($to, $subject, $message, $headers)) {
$file = fopen("mailsentlist.txt","a+"); // add email id to mailsentlist.txt to track the email sent
fwrite($file, $to.",\r\n");
fclose($file);
}
else
{
$file = fopen("notmailsentlist.txt","a+"); // add email to notmailsentlist.txt here which have sending email error
fwrite($file, $to.",\r\n");
fclose($file);
}
if(($i-$count)>=200) // this will send 200 mails from database per execution
{
$filec = fopen("count.txt",'w'); // store current count to count.txt
fwrite($filec, $i);
fclose($filec);
break;
}
}//for end
$filec = fopen("count.txt",'w'); // store fine count to count.txt this will be used as a start point of next execution
fwrite($filec, $i);
fclose($filec);
?>

want to send session values in url

hi i am taking values from a page and getting values in second page whihch is working correctly but i have to send the values in url
<?php
session_start();
$_SESSION["email_address"] = $_REQUEST["email_address"];
echo "Favorite color is " . $_SESSION["email_address"] . ".<br>";
//$errors = '';
$myemail = 'info#abcdef.com';//<-----Put Your email address here.
$to_go="abcdef#gmail.com";
$to = $to_go;
$email_subject = "Contact form submission: aaname";
$email_body = "You have received a new message. ".
" Here are the details: Kindly <a href='localhost/ci/email_wait.php?email_address='.echo $email_address.'&password'=.$password.'>
Click Here</a> to reset your password";
$headers = "From:". $myemail;
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
echo "Mail Sent. Thank you we will contact you shortly.";
?>
NOTE: This code will not work on localhost.
Check out PHP's documentation on string interpolation
You want something like:
$email = "something#somewhere.com";
$body = "Your email address is: $email, hooray!";
echo $body;
Which will output Your email address is: something#somewhere.com, hooray!
Why you echo $email_address and where you initialize your email_address proper way to do like this
$email_body = "You have received a new message. Here are the details: Kindly<a href='localhost/ci/email_wait.php?email_address='".$email_address."'&password='".$password."'>Click Here</a> to reset your password";
and you can also send mail from localhost through smtp settings and put headers also before mail like this
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

PHP Sending Duplicate Emails

After some more troubleshooting I believe I found the problem. We use QR Tags for our product and when a QR code is scanned it takes the user to the URL that runs this script. If I manually type in the URL or if I use our custom built QR scanner app then the user will receive one email. However if I user any other QR scanning app then it will send multiple emails. How can I make it so that this script will run only once each time the URL is loaded even if its from a third party app?
<?php
$queryString = $_SERVER['QUERY_STRING'];
$count=-6;
$id=substr($queryString,$count,6);
//db connection
$db = new mysqli('localhost', '*****', '*****', '*****');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "SELECT * FROM `****` where id = '$id'";
$result = $db->query($query);
$row = $result->fetch_assoc();
$email = $row['email'];
$ownername = $row['ownername'];
$petname = $row['petname'];
//check to see if tag has been registered
if ($email != "") {
//send email
$datetime = date("D M j G:i:s T Y");
$subject = "Alert";
$mailheader.= "From: " . "Tag Team <support#tag.com>\n";
$mailheader.= "X-Sender: " . "support#tag.com\n";
$mailheader.= "Return-Path: " . "support#tag.com\n";
$mailheader .= "Bcc: support#tag.com";
$body .= "Dear " . $ownername . ", \n\n";
$body .= "" . $petname . "'s Tag has just been scanned.\n\n";
$body .= "Click here to Login :\n";
$body .= "http://www.tag.com\n";
$body .= "********************\n\n";
$body .= "Regards,";
$body .= " \n\n";
$body .= "Tag Team";
$body .= " \n\n";
$body .= "Keeping Pets Safe and Found";
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
//end email alert
}
header("Location: http://www.smartphonepettag.com/id/profile.php?id=$id");
mysql_close($db);
?>
In the code snippet I cannot see any reason why your script should be executed more than once but relating to your post yesterday it seems as if something on your mail server is going terribly wrong.
But anyway if it's not an mail server fault the solution would be something like this:
// add this at the very first line
session_start();
// add this in the code
if($_SESSION['send'] != true){
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
$_SESSION['send'] = true;
}
This will make sure that the "mail()" function will never be executed twice for the same user.
You can learn more about Session Variables at the PHP manual.
You could create a flag in your database indicating if the email has been sent. Check the flag before sending the email, set it after you send the email.

Categories