PHP message sending script not working - php

The following script was supposed to send email if all conditions are met and echo "success". The problem here is it is returning "success" but email is not being sent. I tried my best to figure out the problem but can't figure out as I am new to PHP. So I am looking for any possible help. Any help will be appreciated. Thank you in advance
$sql = "SELECT id, username FROM user WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$u = $row["username"];
$emailcut = substr($e, 0, 4);
$randNum = rand(10000,99999);
$tempPass = "$emailcut$randNum";
$hashTempPass = md5($tempPass);
$sql = "UPDATE useroptions SET temp_pass='$hashTempPass' WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$to = "$e";
$from = "auto_responder#geniusfree.net";
$headers ="From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \n";
$subject ="GeniusFree Password Reset";
$msg = '<h2>Hello '.$u.'</h2><p>This is an automated message from GeniusFree. If you did not recently initiate the Forgot Password process, please disregard this email.</p><p>You indicated that you forgot your login password. We can generate a temporary password for you to log in with, then once logged in you can change your password to anything you like.</p><br /><p>Click here now to apply the temporary password shown below to your account</p><p>If you do not click the link in this email, no changes will be made to your account. In order to set your login password to the temporary password you must click the link above.</p>';
if(mail($to,$subject,$msg,$headers)) {
echo "success";
exit();
} else {
echo "email_send_failed";
exit();
}}

Check the MX entry settings. Highest priority is 0. If you are using your mail server in your host. The first entry should be something like this priority number 0 ---> mail.yoursite.com.
Another way to debug this is to use email trace route. You can do it in cpanel.
Hope this helps.

First you need to configure php to send emails from your server ,if you are running code on your local host machine then you have to configure your php.ini file for sending emails and if code is running on web hosting server then contact them for this issue ,
for configuration details you can refer send mail using xampp in php
if you are using another local server like wamp then you have to separately (download) install sendmail utility on your server.
Hope this works for you

do you run it on the local host? if so , it may does not work there , please test it on the Web Host and let me know the result.

Related

sending an email based on data from MySQL table

I've got email function setup and working by setting the code to email a specific email address. However, with this is that it goes to the same email address everytime the submit button is pressed based on the data entered in a text box who the mail comes from.
However, I want to change it so that when a user enters their username in the username box it checks my database table for that username and checks their email address and emails them all the information set for that user.
The code i'm using is ;
$username = $_POST['username'];
$my_query="SELECT * from loanusers where username = '$username'";
$result= mysqli_query($connection, $my_query);
$to = $myrow["emailaddess"];
$subject = 'CSG - Forgotten Password';
$sender = 'CSGLoanSystem#mail.com';
$password = $myrow["password"];
$admin = 'CSGLoanSystem Admin Team';
$body = <<< EMAIL
Hi {$username}, You have recently requested a notification of your password.
The Password registered with account {$username} is $password.
Thanks - {$admin}
EMAIL;
$header = "From:" . $sender;
if ($result):
mail($to, $subject, $body, $header);
$feedback = 'Email Sent';
endif;
At the moment when the submit button is pressed, the page refreshes but nothing actually happens and no email is received at the expected email address?
Pointing to the right direction:
Read up on MySQL and PDO. Also Read up on prepared statements and parameter binding.
Elaborating on the directions given:
There are many ways to connect to a database, and there are many different databases available. One popular database software is called MySQL, and the coding method that is most recommended to connect to that database is PDO for reasons such as having better methods for preventing security breaches.
You can find a lot of online tutorials on how to connect to a database, so I won't go into that, though I will however give you an example of a query you could use to do your email searching, and also I'll include prepared statements and parameter binding since these two details are often misunderstood by a lot of programmers.
If you have the following table:
users
______________________________
| username | email |
|------------+-----------------|
| john44 | abc#gmail.com |
|------------+-----------------|
| adam11 | 123#gmail.com |
|------------+-----------------|
the following code would allow you to retrieve john44's email:
$username = $_POST['username'];//getting the username written in the form
$sql = "SELECT email FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$username]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//here I'm just outputting the obtained email for you to see
//it works, however you would then use the email saved in
//$result['email'] whichever way you want.
echo "email = {$result['email']}<br>";
Edited:
After you edited your code, I noticed you are not fetching the information you queried. Insert the following code after line $result= mysqli_query($connection, $my_query);:
$myrow = mysqli_fetch_assoc($result);

Crons are running but email not sent out

I am running a PHP/MySQL server and am using cron jobs to periodically update my customers as well as send automated newsletters, invoices, etc. However, it does not appear to be working, as emails are not getting sent.
The cron jobs are running (checked the logs).
Invoking the script via the browser results in the emails being sent.
Using SSMTP for email transport.
SPF and DKIM records are in place and correct.
I cannot figure out what is going wrong. Here is pseudocode of the email script:
$override_authentication = true;
require_once('../services/shared/connect.php');
$query = "SELECT * FROM `organizations`";
$orgs = mysqli_query($database,$query);
while ($org = mysqli_fetch_array($orgs)) {
// GENERATE EMAIL CONTENT HERE
// Send email to all users
$query = "SELECT `id`, `email`, `avatar`, `gender`, `phone`, `option_textalerts` FROM `users` WHERE `organization` = " . $org['id'] . " AND `option_scheduling` = 'enabled'";
$users = mysqli_query($database, $query);
while($user = mysqli_fetch_array($users)) {
$message = emailGetHeader("Submit Availability for ".date('F Y', mktime(0,0,0,date('n')+1,1,date('Y'))), $user) . $body . emailGetFooter();
$to = $user['email'];
mail($to,"Submit Availability for ".date('F Y', mktime(0,0,0,date('n')+1,1,date('Y'))),$message,emailGetMeta('Leadsheet <email#leadsheet.us>', 'Leadsheet Automailer <no-reply#leadsheet.us>'));
// If enabled, sent a text alert to the phone number on their account
if ($user['option_textalerts'] == 'availability') {
$phone = preg_replace("/[^0-9]/", "", $user['phone']);
$domains = array('txt.att.net', 'myboostmobile.com', 'sms.mycricket.com', 'tmomail.net', 'vtext.com');
foreach ($domains as $domain) {
mail($phone.'#'.$domain, "Availability Reminder",'Please submit your availability for '.date('F Y', mktime(0,0,0,date('n')+1,1,date('Y'))).' on Leadsheet', emailGetMeta('Leadsheet <txt#leadsheet.us>', 'Leadsheet Automailer <no-reply#leadsheet.us>'));
}
}
}
}
mysqli_close($database);
It looks like you are missing an environment variable. look at phpinfo() and compare with your local environment. Alternatively you can just use wget to emulate a browser loading the page.
After consulting a friend, I discovered the answer. The cron engine was executing the script from the root directory, so the relative file name in the require_once wasn't resolving. Adding a cd command before executing the script solved the issue.

Get all rows into a variable then mailto for each PHP

So, I found this thread (Get all data from mysql row in a variable) but I am too much of a beginner to make it apply easily to my situation. Thank you for helping me out... sorry for the total newb questions.
I have a PHP form that lets the user select one of my tables in a database where email addresses are stored to send an email to each of them. Right now, I have this code:
$recipientid = $_POST['recipientid'];
$body = $_POST['body'];
$subject = $_POST['subject'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: SENDER NAME <senderemail#gmail.com>' . "\r\n";
date_default_timezone_set('America/Los_Angeles');
$time = date('m/d/Y h:i:s a', time());
$sendbody = $body . "<br><br>This is a bulk email announcement sent by
the institution.<br><br>It was sent at " . $time . ". If you have any
questions about this message or wish to unsubscribe, please contact
the institution.";
if($recipientid == 'allstudents'){
// SEE NOTE #2//
$recipientlist = //email addresses
}
$process=explode(",",$recipientlist);
reset($process);
foreach ($process as $to) {
$sent=mail($to,$subject,$sendbody,$headers);
}
if ($sent) { //(success echo goes here... it is quite long so i removed it.)
} else {
echo "Email could not be sent, PLEASE CONTACT US.";
}
What is the easiest way to capture all of the email addresses in the column of the specified table and then loop a mailto for each? I was originally trying to get them all into one string and then explode them as you can see, but that might not be the best solution. Am I on the right track here?
(NOTE #2 FROM IF)
HERE IS WHERE I NEED SOMETHING... I was sort of thinking about trying to use the following. I need it to grab all the emails from the column emailaddresses in the table students. I am using an if statement because there are four other things that $recipientid could equal, and each different one grabs email addresses from a different table.
array pg_fetch_all_columns ( resource $result [, int $column = 3 ] ) But then, I don't know how to get this array to work with my mail. I originally tried to use just a SELECT * from emailaddresses and then use each row somehow but I don't know how to implement that.
YES, I know I am using mysql not mysqli and I know that mailto is probably not the best solution, but it is what I have to work with right now (unless you can suggest an alternative route for the mail loop).
Thank you again! I really want to learn what I am doing, so an explanation would be appreciated:)
(and ps I am using the mail function with the explode because of this article http://tutorial.world.edu/web-development/php-script/how-to-send-out-mass-emails-php-script/)
I might be a little confused about the question. It sounds like you have a database with email address and you want to send an email for each email address. I think you can just do the query SELECT emailaddress from table and cycle through the results and use your mail function each time.
$query = *your select query*
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$sent=mail($row['emailadress'],$subject,$sendbody,$headers);
if ($sent) { //(success echo goes here... it is quite long so i removed it.)
} else {
echo "Email could not be sent, PLEASE CONTACT US.";
}
If you want your user to select the table the email addresses are coming from you can use a form and a variable in the query.
You can use the below piece of code to send the mail.
Consider you have an email field in your table 'students'
then
$sel = mysql_query("select email from students");
while($info = mysql_fetch_assoc($sel))
{
$to = $info['email'];
$sent=mail($to,$subject,$sendbody,$headers);
//---Remaining code goes on
}
try it.

send reminder emails with php and mysql WITHOUT cron-job?

I just made a php script that will send email reminders to admins of a website 2 days before an appointment begins. I was going to automate the script to run through a cron job, only to realise who I am hosting with (crazy domains) does NOT appear to have Cron Jobs
Is there ANY way of doing this without cron-jobs? I do not mind going to a different service provider if that is the case; I have done quite a bit of searching around, and my understanding so far is that I need Cron Jobs for these types of things?
Here is the script I did so far:
<?php include "../connect-to-database.php"; ?>
<?php
$date = date("Y-m-d");
$mod_date = strtotime($date."+ 2days");
$newDate = date("m/d/Y",$mod_date);
$sqlCommand = "SELECT * FROM eventcalender WHERE eventDate='$newDate'" ;
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
if ($count >= 1){
while($row = mysql_fetch_array($query)){
$ID = $row["ID"];
$schedule_title = $row["Title"];
$schedule_description = $row["Detail"];
$importance_level = $row["importance_level"];
$meeting_datetime = $row["eventDate"];
$contacts_involved = $row["contacts_involved"];
$meeting_occurred = $row["meeting_occurred"];
$mid = mysql_insert_id();
$search_output .= "<ul>
<li>
<h4>".$schedule_title."</h4>
<p><b>Time: ".$meeting_datetime."</b></p>
<p>People/Persons involved: ".$contacts_involved."</p>
<p>Meeting Occurred?: ".$meeting_occurred."</p>
<a href='uniqueMeeting.php?ID=".$ID."'>View more details of this meeting</a>
<p><a href='editschedulePage.php?mid=$ID'>Edit This Meeting</a></p>
<p><a href='scheduleList.php?deleteid=$ID'>Delete this meeting</a></p>
</li><br/>
</ul>";
$sendMail = true;
}
}
if($sendMail){
$admin = "SELECT * FROM admin" ;
$queryAdmin = mysql_query($admin) or die(mysql_error());
$adminCount = mysql_num_rows($queryAdmin);
$recipients = array();
if ($count >= 1){
while($row = mysql_fetch_array($queryAdmin)){
$subject ='A-CRM; UpComing Activities';
$msg = $search_output;
$to = $row['email_address'];
mail($to, $subject, $msg);
}
}
}
?>
Yes I do realise I am an absolute horrible person for NOT using mysqli, and I will start to as soon as I finish this website
If the site you're building is visited frequently, you can keep a timestamp (or datetime or whatever) in your database holding the next time the script has to run. Then include the script in your website (every page or just a selection them).
If the current time is equal or greater than the time in the database, run the script and set the time in the database to the value the script has to run next. In this way, the script will be executed by one of the visitors of the site, without them knowing.
Replace
php include "../connect-to-database.php";
with
php include dirname(__DIR__) . "/connect-to-database.php";
Try to add some Observer which will check whether there is a need to send mails.
For example - add into your init file (maybe index.php)
<?php include DIR ."send_mail.php" ?> // your file that you describe in the question.
It will add an additional query to DB since the check will be executed every time the user comes on the page.
I hope it will help you to resolve your issue.
Very simply and effective way using crons. The crons are very simple you will set up date and time cron automatically runs your file. This is guide to using crontab: http://www.adminschoice.com/crontab-quick-reference/

Form processing causing apache to crash?

I use the following code to register users on my site. The problem is that when a user registers apache doesn't respond and crashes.
Is there a break in my code or something I am doing wrong????
<?php
include ('../includes/db_connect.php');
$firstname = $_POST['firstname'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = md5($_POST['password']);
// lets check to see if the username already exists
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
$username_exist = mysql_num_rows($checkuser);
if($username_exist > 0){
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
//include 'register.html';
exit();
}
// lf no errors present with the username
// use a query to insert the data into the database.
$query = "INSERT INTO users (firstname, email, username, password)
VALUES('$firstname', '$email', '$username', '$password')";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "You have successfully Registered";
// mail user their information
//$yoursite = ‘www.blahblah.com’;
//$webmaster = ‘yourname’;
//$youremail = ‘youremail’;
//
//$subject = "You have successfully registered at $yoursite...";
//$message = "Dear $firstname, you are now registered at our web site.
// To login, simply go to our web page and enter in the following details in the login form:
// Username: $username
// Password: $password
//
// Please print this information out and store it for future reference.
//
// Thanks,
// $webmaster";
//
//mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
//
//echo "Your information has been mailed to your email address.";
?>
this script will NOT cause apache to die. on this side theres nothing wrong with it.
however i dont know whats in db_connect.php
the mailing is deactivated, this indeed could take a very long time if the server settings are not correctly. e.g. if the server cant find its fully qualified domain name as your comments suggests.
do you have a session active? this could explain why you cant access any website while the other one is still running and sending the mail and it may look to you like apache crashed.
because you didnt call session_write_close and only once session can be active for writing at a time.
whats definately wrong is the vulnerability to mysql injection.
you absolutely need to change your variables the following way:
$firstname = mysql_real_escape_string($_POST['firstname']);
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
furthermore i would recommend just having a unique que on username and try the insert and see whether you get an error or if you get an mysq_insert_id. let mysql do the job.
but your check is fine too.. but you should have a constraint in the database too, just as a precaution.
and you should trim your values and maby allow only certain chars, its annoying if a username on a website is &%DTRFG$Ä←↓ff

Categories