如何使用 gmail api 在特定日期和时间安排电子邮件?

How to schedule an email at a specific date and time, with the gmail api?

我想问问是否有人知道如何使用 gmail API 安排电子邮件。我正在使用 laravel 8。 例如,我需要的是安排一封电子邮件在特定日期和特定时间发送。我已经有正常发送邮件的功能,但现在我还需要安排发送的功能。如果有人可以帮助我,请指出 gmail api 的示例或功能,我将不胜感激。谢谢。 这是我在 laravel 控制器中的功能:

public function sendGoogleGmail($sender, $to, $subject, $message_text, $files){ 
    session_start();
    
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
       $this->client->setAccessToken($_SESSION['access_token']);
       try {
            $service = new Google_Service_Gmail($this->client);
            $mail = new PHPMailer(true);
            $mail->ContentType = 'text/html';
            $mail->CharSet = "UTF-8";
            $mail->From = $sender;
            $mail->FromName = auth()->user()->name;
            foreach ($to as $key => $email) {
                $mail->AddAddress($email);
            }
            //$mail->AddReplyTo(Contants::FROM, Contants::ALIAS);
            $mail->Subject = $subject;
            $mail->Body = $message_text;

            if(isset($files)){
                $path='files/filesTemplateEmail/';
                foreach($files as $file){
                    $mail->AddAttachment($path . $file->name);
                }
            }
            
            $mail->preSend();
            $mime = $mail->getSentMIMEMessage();
            $mime = rtrim(strtr(base64_encode($mime), '+/', '-_'), '=');
            $message = new Google_Service_Gmail_Message();
            $message->setRaw($mime);
            $service->users_messages->send('me', $message);
            
            
       } catch (Google_Service_Exception $e) {

            // $e->getMessage();
            return false;
       }
       return true;

    }  else {
        return redirect('/oauth');
    } 

很遗憾,Gmail API 不支持此功能。你可以看到关于它的另一个 SO 问题

替代解决方法

最好的替代方法是将电子邮件存储在队列中并在预定时间通过 API 发送它们。

我认为您正在寻找 Queue/Worker/Jobs,Laravel 实现它 开箱即用 , 你可以查看 here.

请记住,要处理您的队列,您的服务器中必须有第二个 php artisan 进程 运行 来处理队列,您也可以使用像 redis 这样的服务来处理它。

希望对你有帮助=)