PHP remainder mail

<?php
// Include your config file
include('config.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

// Function to send email
function sendEmail($to, $subject, $message) {
    $mail = new PHPMailer(true);
    try {
        //Server settings
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = 'mail.supremecluster.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'abc@def.com'; // Replace with your Gmail username
        $mail->Password = 'LR123!'; // Replace with your Gmail password
        $mail->SMTPSecure = 'tls';
        $mail->Port = 465;

        //Recipients
        $mail->setFrom('abc@def.com');
        $mail->addAddress($to); // Add a recipient

        //Content
        $mail->isHTML(true); // Set email format to HTML
        $mail->Subject = $subject;
        $mail->Body    = $message;

        $mail->send();
        echo 'Email has been sent';
    } catch (Exception $e) {
        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}

if (isset($_POST['submit'])) {
  // Retrieve form data
  $date = $_POST['date'];
  $notes = $_POST['notes'];
  $email = $_POST['email'];
  $time = $_POST['time'];

  // Insert data into the database
  $query = "INSERT INTO prospect (date, notes, email, time, email_sent) VALUES ('$date', '$notes', '$email', '$time', 0)";
  mysqli_query($conn, $query);

    // Get current datetime
    // date_default_timezone_set('Asia/Kolkata');
    date_default_timezone_set('UTC');
    $current_datetime = date('Y-m-d H:i:s');

    // Calculate the time difference between current datetime and entered datetime
    $scheduled_datetime = $date . ' ' . $time;
    $time_diff = strtotime($scheduled_datetime) - strtotime($current_datetime);

    if ($time_diff > 0) {
        // If the scheduled datetime is in the future, schedule the email to be sent later
        echo "<script>scheduleEmail('$email', '$time', '$date');</script>";
        echo 
        "<div class='alert alert-success alert-dismissible fade show'>
        Remainder added  successfully! 
        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
        </div>";
        ?>
        <script>
        setTimeout(function () { window.location.href= 'Prospect_notes.php?';}, 1000);
        </script>
        <?php

    } else {
        echo "Invalid date/time entered or date/time already passed.";
    }
}
?>


<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Admin | Dashboard</title>

  <!-- Google Font: Source Sans Pro -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
  <!-- Tempusdominus Bootstrap 4 -->
  <link rel="stylesheet" href="plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">

  <!-- iCheck -->
  <link rel="stylesheet" href="plugins/icheck-bootstrap/icheck-bootstrap.min.css">
  <!-- JQVMap -->
  <link rel="stylesheet" href="plugins/jqvmap/jqvmap.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="dist/css/adminlte.min.css">
   <!-- admin dashboard css-->
   <link rel="stylesheet" href="dist/css/admin-dashboard.css">
  <!-- overlayScrollbars -->
  <link rel="stylesheet" href="plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
  <!-- Daterange picker -->
  <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker.css">
  <!-- summernote -->
  <link rel="stylesheet" href="plugins/summernote/summernote-bs4.min.css">

  <link rel="icon" href="../images/favicon.ico" type="image/x-icon" />
  <script>
        function showAlert(message) {
            alert(message);
        }
    </script>
     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function scheduleEmail(email, time, date) {
            $.ajax({
                type: 'POST',
                url: 'send_email1.php',
                data: {
                    email: email,
                    time: time,
                    date: date,
                    notes: notes
                },
                success: function(response) {
                    console.log(response);
                }
            });
        }
    </script>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

    <nav class="main-header navbar navbar-expand navbar-white navbar-light">
      <!-- Left navbar links -->
        <ul class="navbar-nav">
            <li class="nav-item">
              <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
            </li>
          </ul>
    </nav>
    <!-- /.navbar -->
    <!-- Main Sidebar Container -->
    <aside class="main-sidebar sidebar-dark-indigo elevation-4">
      <!-- Brand Logo -->
      <a href="" class="brand-link">
        <!-- <img src="dist/img/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> -->
        <span class="brand-text font-weight-light">Admin Dashboard</span>
      </a>

      <!-- Sidebar -->
      <div class="sidebar">
        <!-- Sidebar Menu -->
       <nav class="mt-4">
          <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
            <!-- Add icons to the links using the .nav-icon class
                with font-awesome or any other icon font library -->
            <li class="nav-item">
              <a href="index" class="nav-link">
                <i class="nav-icon fas fa-tachometer-alt"></i>
                <p>
                  Main Dashboard
                </p>
              </a>
            </li>
            <li class="nav-item">
              <a href="salesform" class="nav-link ">
                <i class="nav-icon fa fa-check-square"></i>
                <p>
                 Sales Form
                </p>
              </a>
            </li>
            <li class="nav-item">
              <a href="generalproduction" class="nav-link ">
                <i class="nav-icon fa fa-industry"></i>
                <p>
                  General Production
                </p>
              </a>
            </li>
            <li class="nav-item">
              <a href="admin"  class="nav-link ">
                <i class="nav-icon fas fa-user-circle"></i>
                <p>
                  Setup Users Admin
                </p>
              </a>
            </li>
              <li class="nav-item">
              <a href="company" class="nav-link ">
                <i class="nav-icon fas fa-building"></i>
                <p>
                 Companies We Sell For
                </p>
              </a>
            </li>
            <li class="nav-item">
              <a href="leadsource" class="nav-link ">
                <i class="nav-icon fas fa-quote-left"></i>
                <p>
                 Lead Sources
                </p>
              </a>
            </li>
            <li class="nav-item">
              <a href="prospect.php" class="nav-link nav-link-width active">
                <i class="nav-icon fas fa-calendar-check"></i>
                <p>
                Customer Action Reminder
                </p>
              </a>
            </li>
            <li class="nav-item">
              <a href="logout" class="nav-link">
                <i class="nav-icon fas fa-power-off"></i>
                <p>
                  Logout
                </p>
              </a>
            </li>     
          </ul>
        </nav>
        <!-- /.sidebar-menu -->
      </div>
      <!-- /.sidebar -->
    </aside>

  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1>Prospects</h1>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="index">Main Dashboard</a></li>
              <li class="breadcrumb-item active">Prospects</li>
            </ol>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content ">
    <!-- Form -->
    
    <form enctype="multipart/form-data" method="post" id="emailForm">
      <div class="row">
        <div class="col-md-12">
          <div class="card card-yellowclr">
            <div class="card-header">
              <h3 class="card-title"></h3>
            </div>
            <div class="card-body">
              <div>
              <div class="row justify-content-center">
    <div class="col-md-6">
        <div class="form-group">
            <label>Date</label>
            <input type="date" class="form-control" value="" required="" name="date" min="1900-01-01" max="2099-12-31" id="date">
        </div>
    </div>
</div>
            <div class="row justify-content-center">
                <div class="col-md-6">
                  <div class="form-group">
                    <label>Notes</label>
                    <textarea id="notes" name="notes" class="form-control" id="notes"></textarea>
                  </div>
                  <!-- /.form-group -->
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-6">
                  <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control" value="" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" name="email" id="email">
                  </div>
                  <!-- /.form-group -->
                </div>
                <!-- /.col -->
              </div>
            </div> 
            <div class="row justify-content-center">
                <div class="col-md-6">
                  <div class="form-group">
                    <label>Time</label>
                    <input type="time" class="form-control" value="" name="time" id="time">
                  </div>
                  <!-- /.form-group -->
                </div>
                <!-- /.col -->
              </div>
            </div> 

            <div class="row pb-lg-4 m-2">
              <div class="col-12">
                <a href="prospect.php" class="btn btn-secondary">Back</a>
                <input type="submit" name="submit"value="Submit" class="btn btn-success float-right" onclick="submitForm()">
              </div>
            </div>
            <!-- col-->

</div>
 

            </div>
            <!-- /.card-body -->
            <!-- <div class="card-footer ">
              <div class="row">
                  <div class="col-12">
                    <a href="index" class="btn btn-secondary">Back</a>
                    <input type="submit" value="submit" name="submit" class="btn btn-success float-right">
                  </div>
                  
              </div>
            </div> -->
            
          </div>
          <!-- /.card -->
        </div>
      </div>
    </form>
    </section>
    <!-- /.content -->
  </div>

</div>



<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
  $.widget.bridge('uibutton', $.ui.button)
</script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- ChartJS -->
<script src="plugins/chart.js/Chart.min.js"></script>
<!-- Sparkline -->
<script src="plugins/sparklines/sparkline.js"></script>
<!-- JQVMap -->
<script src="plugins/jqvmap/jquery.vmap.min.js"></script>
<script src="plugins/jqvmap/maps/jquery.vmap.usa.js"></script>
<!-- jQuery Knob Chart -->
<script src="plugins/jquery-knob/jquery.knob.min.js"></script>
<!-- daterangepicker -->
<script src="plugins/moment/moment.min.js"></script>
<script src="plugins/daterangepicker/daterangepicker.js"></script>
<!-- Tempusdominus Bootstrap 4 -->
<script src="plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
<!-- Summernote -->
<script src="plugins/summernote/summernote-bs4.min.js"></script>
<!-- overlayScrollbars -->
<script src="plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="dist/js/pages/dashboard.js"></script>
</body>
</html>

<script>
document.onkeydown = function(e) {
  if(event.keyCode == 123) {
     return false;
  }
  if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) {
     return false;
  }
  if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)) {
     return false;
  }
  if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) {
     return false;
  }
  if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) {
     return false;
  }
}
</script>
<script>
        function submitForm() {
            var email = $('[name="email"]').val();
            var date = $('[name="date"]').val();
            var time = $('[name="time"]').val();
            var notes = $('[name="notes"]').val();
            $.ajax({
                type: 'POST',
                url: 'send_email1.php',
                data: $('#emailForm').serialize(),
                success: function(response) {
                    console.log(response);
                }
            });
        }
    </script>

Hi everyone,

I have a basic knowledge of PHP and need your help with a specific task. Here’s the situation: I have a form with four fields—date, notes, email, and time—and a submit button. When the admin fills out the form and clicks submit, the data should be inserted into the database, and an email should be sent at the specified date and time, without using a cron job. Is this possible? If so, could you provide a solution?

Additionally, my client is in the US, so I need to ensure the time is set according to their time zone. Could you also explain how to handle the time declaration?

Thank you in advance for your assistance.

‘without using the exact tool designed for the job’.

Yeah, no. You’re going to need something to be running on the computer that’s monitoring the time.

Universal Coordinated Time. It’s coordinated. For a reason.

1 Like

Time zone setting: To set the time zone in PHP, use this code:

date_default_timezone_set('America/New_York'); // or your client's time zone

Here’s a sample code structure:

<?php
// Include your database connection
include('config.php');

// Database insertion
if (isset($_POST['submit'])) {
    $date = $_POST['date'];
    $notes = $_POST['notes'];
    $email = $_POST['email'];
    $time = $_POST['time'];

    $scheduled_time = $date . ' ' . $time;

    $query = "INSERT INTO scheduled_emails (email, notes, scheduled_time, email_sent) VALUES ('$email', '$notes', '$scheduled_time', 0)";
    mysqli_query($conn, $query);
}

// Content for send_scheduled_emails.php
function sendScheduledEmails() {
    global $conn;
    date_default_timezone_set('America/New_York');
    $current_time = date('Y-m-d H:i:s');

    $query = "SELECT * FROM scheduled_emails WHERE email_sent = 0 AND scheduled_time <= '$current_time'";
    $result = mysqli_query($conn, $query);

    while ($row = mysqli_fetch_assoc($result)) {
        // Email sending process here
        sendEmail($row['email'], 'Subject', $row['notes']);

        // Mark email as sent
        $update_query = "UPDATE scheduled_emails SET email_sent = 1 WHERE id = " . $row['id'];
        mysqli_query($conn, $update_query);
    }
}

// Email sending function
function sendEmail($to, $subject, $message) {
    // Use PHPMailer or another email library to send the email
}

// Call the function to send scheduled emails
sendScheduledEmails();
?>

Note that the above code will only send emails when the page is called; you still need something to call the page on the specified schedule.

If you rely on it being hit by random views, you could run into a problem where two users hit the page at the exact same time, pull a resultset of 0’s, and both send emails, while setting them to 1’s. You could also ‘miss’ the sending timeline by… minutes, hours, days… if noone hits the page.

It’s not recommended to use end-users’ actions as a timing trigger.

1 Like