With the rapid development of the internet, email has become an essential communication tool for both work and daily life. Whether for contract exchange or subscription notifications, scheduled email sending greatly enhances user experience and efficiency. This article will explain how to implement scheduled email sending using PHP.
First, set up a PHP development environment and ensure that a mail transfer agent (such as sendmail or Postfix) is installed on your server. If not installed, configure it according to your system requirements.
There are multiple PHP libraries for sending emails, including PHPMailer and SwiftMailer. These provide stable and easy-to-use APIs to simplify development. This article uses PHPMailer as an example.
Download the latest version of PHPMailer from the official GitHub repository. After extraction, copy the folder into your project directory and include the required class files using require_once.
<?php require_once 'path/to/PHPMailer/PHPMailer.php'; function sendEmail($recipient, $subject, $body) { $mail = new PHPMailerPHPMailerPHPMailer(); // Configure SMTP server $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'your-email@example.com'; $mail->Password = 'your-email-password'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; // Set sender and recipient $mail->setFrom('your-email@example.com', 'Your Name'); $mail->addAddress($recipient); // Set email subject and body $mail->Subject = $subject; $mail->Body = $body; // Send the email if ($mail->send()) { return true; } else { return false; } } ?>
Using PHP with Crontab, you can schedule email sending tasks. The following example shows how to schedule sending based on a specified time:
<?php require_once 'path/to/PHPMailer/PHPMailer.php'; function scheduleEmail($recipient, $subject, $body, $scheduleTime) { $currentTimestamp = time(); $targetTimestamp = strtotime($scheduleTime); if ($targetTimestamp <= $currentTimestamp) { // Target time passed, send immediately return sendEmail($recipient, $subject, $body); } else { $delay = $targetTimestamp - $currentTimestamp; // Add task to Crontab exec("echo 'php path/to/scheduled_email.php $recipient \"$subject\" \"$body\"' | at now + $delay seconds"); return true; } } ?>
A PHP script is needed to handle scheduled tasks, calling the email sending function with passed parameters:
<?php require_once 'path/to/send_email.php'; $scheduleRecipient = $argv[1]; $scheduleSubject = $argv[2]; $scheduleBody = $argv[3]; sendEmail($scheduleRecipient, $scheduleSubject, $scheduleBody); ?>
Following these steps, you can implement scheduled email sending with PHP. For real projects, feel free to adjust and expand the functionality to meet more complex needs. Hopefully, this guide provides useful insight to assist your email development tasks.