如果您知道如何填充“notify_user”表,那么这些是我为您重现解决方案示例的步骤。我在运行 sendmail 守护程序的 VPS 服务器上执行此操作。
# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 167
Server version: 5.5.40-0ubuntu0.14.04.1 (Ubuntu)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database stack_mail_db;
Query OK, 1 row affec`enter code here`ted (0.05 sec)
mysql> grant all privileges on stack_mail_db.* to 'stack_mail_usr'@'localhost' identified by 'stack_mail_pass';
Query OK, 0 rows affected (0.11 sec)
mysql> use stack_mail_db;
Database changed
mysql> create table notify_user( id int not null auto_increment primary key, user_name tinytext, user_email tinytext );
Query OK, 0 rows affected (0.28 sec)
创建此示例数据库后,我们应该使用至少 2 个用户(用于测试)填充工作电子邮件。我在这里更改了我使用的实际电子邮件。
mysql> insert notify_user (user_name, user_email) values ('test1', 'test1@test.com');
Query OK, 1 row affected (0.18 sec)
mysql> insert notify_user (user_name, user_email) values ('test2', 'test2@test.net');
Query OK, 1 row affected (0.03 sec)
现在我们应该编写一个脚本来获取这些详细信息并发送电子邮件:
# vim cron_email.php
<?php
$host = 'localhost';
$user = 'stack_mail_usr';
$pass = 'stack_mail_pass';
$dbname = 'stack_mail_db';
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
trigger_error('DB connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$query = 'select * from notify_user';
$res = $conn->query($query);
if ($res === false) {
trigger_error('Failed query: ' . $query . ' Error: ' . $conn->error, E_USER_ERROR);
}
$headers = 'From: admin@example.com' . "\r\n" .
'Reply-To: admin@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$res->data_seek(0);
while ($row = $res->fetch_assoc()) {
$to = $row['user_email'];
$subject = 'Notification for ' . $row['user_name'];
$message = 'Hello ' . $row['user_name'];
$mail = mail($to, $subject, $message, $headers);
if ($mail) {
$conn->query('delete from notify_user where id=' . $row['id']);
} else {
echo "Email failed\n";
}
}
现在是时候将这个脚本放在 cron 上:
# crontab -e
0 0 * * * php -f /path/to/cron_email.php
这将在每个午夜运行您的脚本。如果您想设置更具体的时间,请查看本教程:
http ://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses /
希望这会有所帮助^)