Skip to content
Advertisement

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

I want to ask if anyone knows how to schedule an email with the gmail API. I am using laravel 8. What I need is, for example, to schedule an email to be sent on a specific day and at a specific time. I already have the function to send mail normally but now I also need the function to schedule a send. I appreciate if someone can help me, indicate an example or function of the gmail api for this. Thanks. This is my function in the laravel controller:

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');
    } 

Advertisement

Answer

I think that you are looking for a Queue/Worker/Jobs, Laravel implements it out of the box, you can check it here.

Remember that to process your queue you must have a second php artisan process running in your server to handle the queue, you could also use services like redis to process it.

Hope it helps you =)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement