如何按设置的日期和时间自动将电子邮件发送到 PHP 中的多个用户电子邮件

How to send email to multiple user email in PHP by set date and hour automatically

我想通过用户设置日期自动将电子邮件发送到 PHP 中的多个用户电子邮件我的意思是用户从输入日期中选择日期和时间并将其保存在数据库中然后我想要在那个日期发送电子邮件 有没有办法 PHP 自动完成这项工作,因为我自己手动完成这项工作并且用户数量正在增加,也许我们必须在一天中的任何几秒钟发送电子邮件并且当我成功时,我想在 Laravel 5.8 框架中完成这项工作。

我在 PHP 文件中使用的代码和 运行 手动使用的代码如下:

(我通过选择日期和时间从数据库中获取 $UsersEmail 数组,这就像我在代码中编写的数组)。

$UsersEmail = array(
    0 => 'user1@example.com',
    1 => 'user2@site.com',
    2 => 'user3@test.com',
    3 => 'user4@somesite.com',
    4 => 'user5@anohtersite.com',
);

$AllEmail = '';

foreach($UsersEmail as $user){
    $AllEmail .= $user.', ';
}

$to = $AllEmail;

$subject = 'Send Email';

$message = 'This is text message';

$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=utf-8';

$headers[] = 'From: My site <info@mysite.com>';

mail($to, $subject, $message, implode("\r\n", $headers));

我以后想在 Laravel5.8 框架中做这项工作

我的PHP版本是7.2.7,以后想用的Laravel版本是5.8。

您可以安排可能每分钟或每小时运行一次的命令,检查是否有任何邮件在适当的时间发送。在您的 table 中,您将有一个标志,告诉您邮件是否已发送,以免向用户发送垃圾邮件或您想要的任何逻辑。获得用户后,派遣工作。

SendUserMail 命令

public function handle()
{
    $users = User::where('mail_sent', false)->whereDate('mail_send_date', '<=', Carbon::now())->get();
    ProcessUserMails::dispatch($users);
}

内核中你必须注册命令

protected function schedule(Schedule $schedule)
{
    $schedule->command('send-user-mail')->hourly();
}

ProcessUserMails 作业

public function handle()
{
    foreach ($this->users as $user) {
        $user->notify(new SendMailNotification($user));
        $user->update(['mail_sent', true);
    }
}

SendMailNotification

public function toMail($notifiable)
{
    return (new UserMail($this->user))->to($notifiable->email);
}

用户邮箱

public function build()
{
    return $this->subject('User Custom Email')
        ->markdown('emails.user.custom_mail');
}

这可以作为您的起点。但是,请务必查看有关创建命令和通知的 Laravel 文档,因为我只包含了代码片段。