Gmail API: 400 bad request when trying to send an email (PHP code)

后端 未结 5 588
一整个雨季
一整个雨季 2020-12-01 17:55

I expected the code below to send an email, but I\'m only getting this:

An error occurred: Error calling POST https://www.googleapis.com/gmail/v1/us

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 18:47

    This is a full working example, just make sure to change all the appropriate info and use PHPMailer to format a valid mail.

    sub = FROM;
    
    $client = new Google_Client();
    
    $client->setAssertionCredentials($credentials);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion();
    }
    
    function create_message() {
        $mail = new PHPMailer();
        $mail->setFrom(FROM, 'John Doe 1');
        $mail->addAddress(TO, 'John Doe 2');
        $mail->Subject = 'Saying Hello';
        $mail->Body = 'This is a message just to say hello. So, "Hello"';
        $mail->preSend();
        $mime = $mail->getSentMIMEMessage();
        return urlsafe_b64encode($mime);
    }
    
    function sendMessage($service, $userId, $message) {
        try {
            $message = $service->users_messages->send($userId, $message);
            print 'Message with ID: ' . $message->getId() . ' sent.';
            return $message;
        }
        catch(Exception $e) {
            print 'An error occurred: ' . $e->getMessage();
        }
    }
    
    function urlsafe_b64encode($string) {
        $data = base64_encode($string);
        $data = str_replace(array('+','/','=') , array('-','_','') , $data);
        return $data;
    }
    
    $service = new \Google_Service_Gmail($client);
    
    $msg = new \Google_Service_Gmail_Message();
    $msg->setRaw(create_message());
    
    sendMessage($service, 'me', $msg);
    ?>
    

提交回复
热议问题