JhonPeter
JhonPeter

Reputation: 31

How to send email on a specific date?

I have a php form that sends emails however I would like to use specified dates as a parameter to send the email for example

?php
$Cristimas = '2021-12-25'; 
$time = strtotime($Cristimas);
while(date('m-d') == date('m-d', $time)) {
    



if(isset($_POST['submit'])){
    $to =  $_POST['email']; // this is your Email address
    $from = "[email protected]"; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
 
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
}

?>

Upvotes: 1

Views: 1746

Answers (1)

Oliver Kucharzewski
Oliver Kucharzewski

Reputation: 2645

Theres many ways. But they will generally require an external worker of some sort. Running an infinite loop on PHP would not be an effective method and can consume memory unnecessarily.

Cronjobs are a way to achieve this, you can run your script every few minutes and see if the desired time has been achieved yet.

This is a great resource for Cronjobs - Crontab.guru

To enter a cronjob, write crontab -e in a Linux based system.

Then you can run your script on an interval (in this case, every 1 minute):

*/1 * * * * /usr/bin/php /opt/test.php

You can also use frameworks like Laravel to manage tasks using these cronjobs, in an easier fashion.

https://laravel.com/docs/8.x/scheduling

Upvotes: 0

Related Questions