我的问题是关于通过PHP快速入门实现白名单功夫

时间:2019-02-10 10:04:42

标签: php google-api gmail google-oauth gmail-api

我想将PHP QuickStart与Gmail API结合使用以实现白名单或黑名单功能。如果发件人位于黑名单中,它将自动成为垃圾邮件,或者只有在该服务中注册的Gmail才能相互发送信件。我们怎样才能做到这一点?谢谢。

我已经实施了回复电子邮件。

<?php
require_once __DIR__.'/vendor/autoload.php';
session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setAccessType("offline");
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Gmail::MAIL_GOOGLE_COM);

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

  if ($client->getAccessToken()) {

            $_SESSION['access_token'] = $client->getAccessToken();

            // Prepare the message in message/rfc822
           if (isset($_SESSION['gmail_access_token']) &amp;&amp; !empty($_SESSION['gmail_access_token']) ) {
  
    $client->setAccessToken($_SESSION['gmail_access_token']);
    $objGMail = new Google_Service_Gmail($client);
  
    $strSubject = 'this is test email message' . date('M d, Y h:i:s A');
  
    $strRawMessage = "From: My Mail <myemail@gmail.com>\r\n";
    $strRawMessage .= "To: My Mail <noreply@gmail.com>\r\n";
    $strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
    $strRawMessage .= "MIME-Version: 1.0\r\n";
    $strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
    $strRawMessage .= "this is a test !\r\n";
  
    //Users.messages->send - Requires -> Prepare the message in message/rfc822
    try {
        // The message needs to be encoded in Base64URL
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);
  
        //The special value **me** can be used to indicate the authenticated user.
        $objSentMsg = $objGMail->users_messages->send("me", $msg);
  
        print('Message sent object');
        print($objSentMsg);
  
    } catch (Exception $e) {
        print($e->getMessage());
        unset($_SESSION['gmail_access_token']);
    }
}
else {
    // Failed Authentication
    if (isset($_REQUEST['error'])) {
        //header('Location: ./index.php?error_code=1');
        echo "error auth";
    }
    else{
        // Redirects to google for User Authentication
        $authUrl = $client->createAuthUrl();
        header("Location: $authUrl");
    }
}

如果有一个实现,请告诉我。谢谢。

0 个答案:

没有答案