sending email for birthday don't show emails - php

I have issue with email in my table when I try to send mails for birthdays..
Here is the printscreen, if you see the table in the right, there are 2 users with birthdays but in the input below of div error is empty... and say "there is not birthday for today":
<?php
$sql = $conn->prepare("SELECT email FROM USERS WHERE f_nac >= CURDATE() AND f_nac < CURDATE() + INTERVAL 1 DAY ORDER BY f_nac ASC");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$email = ($row['email'].", ");
}
$largo=strlen($email);
if ($largo>2)
$email=substr($email,0,$largo-2);
} else {
echo '<div class="alert alert-danger">No hay cumpleaƱeros!</div>';
};
?>
<input type="text" id="email" name="email" value="<?php echo $email; ?>" />
How can I show the emails to send the mail to them?
the two users have emails and the row in the table is "f_nac" with type "date"

CUR_DATE() is in 2014, the birthdays are in 1975 and 1978. You have to ignore the year when you're comparing.
SELECT email
FROM USERS
WHERE MONTH(f_nac) = MONTH(NOW()) AND DAY(f_nac) = DAY(NOW())
In your while loop you're overwriting $email, not appending to it. It should be:
$email = '';
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$email .= ($row['email'].", ");
}

What you are doing currently is extracting the data from SQL (daily) and composing and email to send the wish manually daily. What if I suggest you a better approach ?
There is an application called Wishing Application which can send birthday and work anniversary mailer with a breeze.
At minimal it just need two things excel file with wish details (Date, name, email) and a configuration file (application.properties) and that is it, you are good to go.
Further there various options to run the application locally (Command line, foreground, background, docker, windows scheduler, unix cron etc) Cloud.
Application is highly configurable , you can configure various details like:
Workbook loading options
Image options to send with wishes.
SMTP Configurations
Other application level configurations like, when to send wish, belated wish, logging etc.
Disclaimer : I am the owner of the application

Related

php - phpMailer Cron add's an email to the queue while it shouldn't

I have a script that periodically (every ~5 minutes) requests a bunch of data from an API and possibly sends a email.
However I recently got contacted by the server administrator that there a huge amount of queued mails which will never be sent because of the Cron.
However as it stands right now it should never send the emails because it should never pass the if-statements in which the mailing code is placed.
Script more or less does the same thing twice, but with some different emails:
/* Paging - Every ~15 minutes, during non-working-times, for all dashboards that have pagerservice enabled. */
$queryPagerservice = mysqli_query($dbcon, "SELECT `id`, `text` FROM `dashboard` WHERE `pagerservice`=true AND (`last_pager` < NOW() - INTERVAL ".PAGER_INTERVAL." MINUTE OR `last_pager` IS NULL)");
$timeNow = date("Gi");
while ($pagerservice = mysqli_fetch_array($queryPagerservice, MYSQLI_ASSOC)) {
echo '1.'; //Does the script hit this code?
$issues = new Issues($pagerservice['id'], 'all', $dbcon);
$array = $issues->getIssues();
if ((count($array['aaData']) > 0) && ($timeNow > WORK_START && $timeNow < WORK_END)) {
mysqli_query($dbcon, "UPDATE `dashboard` SET `last_pager`=NOW() WHERE `id`='".$pagerservice['id']."'");
$date = date('d-m-Y H:i:s');
$message = "There are ".count($array['aaData'])." problems in '".$pagerservice['text']."'.";
echo '2.'; //Does the script hit this code?
require_once('phpmailer/PHPMailerAutoload.php');
$pagerMail = new PHPMailer;
$pagerMail->isSMTP();
$pagerMail->Host = MAILSERVER_ADDRESS;
$pagerMail->Port = MAILSERVER_PORT;
$pagerMail->setFrom('pagerservice#example.com', 'EXAMPLE Pager');
$pagerMail->addReplyTo('noreply#example.com', 'No Reply');
$pagerMail->addAddress(PAGE_EMAIL, 'pagerservice');
$pagerMail->addAddress(PAGER_PHONE.'#'.PAGER_PROVIDER, 'pagerservice');
$pagerMail->Subject = 'pagerservice';
$pagerMail->Body = $message;
$pagerMail->AltBody = $message;
$pagerMail->send();
}
}
/* Notifications - Every ~15 minutes, during working hours, for all dashboards that have notifications enabled. */
$queryNotification = mysqli_query($dbcon, "SELECT `id`, `text` FROM `dashboard` WHERE `notification`=true AND (`last_notification` < NOW() - INTERVAL ".NOTIF_INTERVAL." MINUTE OR `last_notification` IS NULL)");
$timeNow = date("Gi");
while ($notifications = mysqli_fetch_array($queryNotification, MYSQLI_ASSOC)) {
echo '3.'; //Does the script hit this code?
$issues = new Issues($notifications['id'], 'all', $dbcon);
$array = $issues->getIssues();
if ((count($array['aaData']) > 0) && ($timeNow > WORK_START && $timeNow < WORK_END)) {
mysqli_query($dbcon, "UPDATE `dashboard` SET `last_notification`=NOW() WHERE `id`='".$notifications['id']."'");
$date = date('d-m-Y H:i:s');
$message = "(Notif) There are ".count($array['aaData'])." problems in '".$pagerservice['text']."'.";
echo '4.'; //Does the script hit this code?
require_once('phpmailer/PHPMailerAutoload.php');
$notifMail = new PHPMailer;
$notifMail->isSMTP();
$notifMail->Host = MAILSERVER_ADDRESS;
$notifMail->Port = MAILSERVER_PORT;
$notifMail->setFrom('notifications#example.com', 'EXMAPLE Notificator');
$notifMail->addReplyTo('noreply#example.com', 'No Reply');
$notifMail->addAddress(NOTIF_EMAIL, 'notifications');
$notifMail->Subject = 'notification';
$notifMail->Body = $message;
$notifMail->AltBody = $message;
$notifMail->send();
}
}
Attempted fix: I moved the require_once() call to within the if-statement. This didn't fix it.
There is no other code in the script that is in any way related to sending email's. And the code that is e-mail related isn't executed (as shown by the fact that neither 1., 2., 3. nor 1. is echoed).
I am looking for any tips as to what can cause the cron script to queue an email that is never sent by the SMTP server.
Cron jobs have no user interface, so if the script outputs anything to the stderror or stdoutput it will cause the cron system to generate an email, to contain that output. This is how you would know your cron is having problems, or how you monitor things like "I did 10 things this run" type of stuff.
It looks to me as if your script has some kind of output either reporting errors or doing your echo '1.' debugging code or something similiar.
First I would check all the code you say it is running for anything like echo or print etc etc, anything that would normally write info to the terminal, and remove/rethink it.
Then change the cron's config to send these emails to a valid email address that you actually monitor, so you know when your script is trying to tell you something.

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.

Error in script sending automatic birthday wish to a registered user in php

I have written the script of sending automatic e-mail for a given date. I have already set up the cron job to execute this once a day for a given time. But it is not working. Can anyone show me the error here. I'm really new to this.
What I'm really supposed to do is to send an automatic email to a user on their birthday
<?php
$host="mysql117.000webhost.com/";//hostname
$username="abc";//mysql_username
$password="123";//mysql_password
$dbname="abc";//Database name
$tbl_name="customer_info";//table name
$date = date("2005-09-23"); //here my date format in my DB is 2010-09-30
$link = mysqli_connect('$host','$username','$password','$dbname');
if($link && mysqli_select_db('$dbname', $link))
{
$grabBday = "SELECT b_day,DATE_FORMAT(b_day,'2015-%m-%d') FROM customer_info where b_day = '2002-09-24'";
//here it will take the name of the person whose bday is on a particular date,I just hard coded this date to check if this is working
if($rs = mysqli_query($link, $grabBday))
{
while(mysqli_fetch_array($rs))
{
mail('abc92#yahoo.com', 'HAPPY BIRTHDAY', 'Many Happy Returns of the day');
}
}
} ?>
I am seeing logical difference as you are searching where b_day=$date where $date='2015-09-23' but dob can be '2002-09-23' or '1997-09-23' etc. so you will not get desired output, so you can change your query as per below if everything other than it is fine.
SELECT * FROM
tbl_name
WHERE CONCAT(YEAR(CURDATE()),DATE_FORMAT(b_day,'-%m-%d')) = $date

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/

Only members can submit this form php

New to php. I have a form that is only for members to submit. What php code do I need for the form to check that the email address on the form is found my members database and then its okay to submit the form?
If email address is not in the members database then I want to echo "Only members can submit this form." What php code do I need to connect to database in the form and do the check so I don't get forms submitted from non members?
Thanks
At the top of your php file you could do something like this:
if(isset($_POST['email'])) {
mysql_connect("hostname","username","password");
$result = mysql_query("SELECT * FROM users WHERE email = '".mysql_real_escape_string($_POST['email'])."'");
if($row = mysql_fetch_array($result)) {
// found email
} else {
// email wasn't found
}
}
Of course you would need to replace the hostname, username and password to correct values, also you should change the users and email in the select query to the name of your table and field.
Here is a dummy form:
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<input type="text" name="email" />
<input type="submit" value="Send" />
</form>
You want to study Mysql query and other mysql functions. The code would basically look like:
$c = mysql_connect( ...);
mysql_select_db( 'database', $c);
$q = mysql_query( "SELECT COUNT(*) FROM users WHERE email = '" .
mysql_real_escape_string( $_POST['email'],$c) . "'");
$row = mysql_fetch_row( $q);
if( $row[0]){
echo "Thanks for submitting...";
} else {
echo "Only members...";
}
This is only brief example which is far from perfection but I think it's good place for you to start.
If someone is a registered member that implies you're very likely using a $_SESSION['id_member'] variable.
This will set the cookie's name that can be seen by the client to 'member'...
if (!headers_sent() && !isset($_SESSION))
{
session_name('member');
}
...then when a user authenticates assign a session variable and their permission...
$_SESSION['member_id'] = $mysql_row['id'];
$_SESSION['member_status'] = $mysql_row['id'];
Here is a status hierarchy that you might use or change but it should be a good point of reference...
10 - Super Admin (only you)
9 - Admin// mid-level admin
8 - Assistant//restrictive admin
7 - Moderator//Don't give this status to any jerks
6 - Premium Member//they gave you money!
5 - Registered Member//normal account status
4 - Frozen Account//not banned but did something wrong, will "thaw"
3 - Unverified Email Address//registered but did not verify email
2 - Unregistered Visitor//human
1 - Good Bots
0 - Banned
Generally first determine how to catch the form...
if ($_SERVER['REQUEST_METHOD']=='GET')
{
}
else if ($_SERVER['REQUEST_METHOD']=='POST')
{
if (isset($_POST['submit_button_name_value'])) {blog_post_ajax_comment();}
}
I add the name="value" attribute/value to submit buttons, why? Have two submit options (preview and publish in example) you may want to have the server trigger one function or the other, VERY simple and valid (X)HTML.
You should check if the variable isset (keep permissions in mind).
Then check if their user permissions are adequate, you can use a simple integer to represent this.
Then wrap the isset and permission if statements around two things, one the form and secondly make sure you use these conditions when PROCESSING the form.
I always test against things to reject and throwing in database query error handling to give you a little extra boost...
//function module_method_ajax_purpose()
function blog_post_ajax_comment()
{
if (!isset($_SESSION['member'])) {http_report('403',__FUNCTION__,'Error: you must be signed in to do that.');}
else if ($_SESSION['member_status']<=4) {http_report('403',__FUNCTION__,'Error: permission denied; your account has been flagged for abuse.');}
else if (flood_control($datetime,'60')!=1) {http_report('403',__FUNCTION__,'Error: you can only post a comment once every X seconds.');}
else if (!isset($_POST['post_form_name_1']) || !isset($_POST['post_form_name_2'])) {http_report('403',__FUNCTION__,'Error: permission denied.');}
else
{
// NOW process
$query1 = "SELECT * FROM table";
$result1 = mysql_query($query1);
if ($result1)
{
//successful, increment query number for further queries
}
else {mysql_error_report($query1,mysql_error(),__FUNCTION__);}
}
Error reporting is VERY powerful, use it for HTTP, JavaScript, PHP and MySQL. You could also benefit from my answer about real-time log reading here: jQueryUI tabs and Firefox: getBBox broken?

Categories