zoukankan      html  css  js  c++  java
  • Google Mail in PHP

    holder

      1 <?php
      3 include_once "templates/base.php";
      4 session_start();
      5 
      6 require_once realpath(dirname(__FILE__)).'/../src/Google/autoload.php';
      8 $client_id     = "xxxxxx";
      9 $client_secret = "xxxxxx";
     10 $client_uri    = "http://localhost/405/gmail/example/Email.php";
     12 /************************************************
     13   Make an API request on behalf of a user. In this case we need to have a valid OAuth 2.0 token for the user, so we need to send them
     16   through a login flow. To do this we need some information from our API console project.
     18  ************************************************/
     19 $client = new Google_Client();
     20 $client->setClientId($client_id);
     21 $client->setClientSecret($client_secret);
     22 $client->setRedirectUri($client_uri);
     23 $client->addScope("https://mail.google.com/"); // change to calendar scope if you are using calendar api
     24 /************************************************
     25   When we create the service here, we pass the client to it. The client then queries the service for the required scopes, and uses that when
     28   generating the authentication URL later.
     29  ************************************************/
     30 $gmail_service = new Google_Service_Gmail($client);    //1.create google_service_gmail
     31 /************************************************
     32   If we're logging out we just need to clear our local access token in this case
     34  ************************************************/
     35 if (isset($_REQUEST['logout'])) {
     36   unset($_SESSION['access_token']);
     37 } 
     39 /************************************************
     40   If we have a code back from the OAuth 2.0 flow, we need to exchange that with the authenticate() function. 
        We store the resultant access token bundle in the session, and redirect to ourself.
    41 ************************************************/ 42 if (isset($_GET['code'])) { // 4. After we login or verify sucuessly. we got a code back from OAuth 2.0 43 $client->authenticate($_GET['code']); 44 $_SESSION['access_token'] = $client->getAccessToken(); 45 $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; 46 header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); //5. After getting token and setting token,redirect to self 47 } 49 /************************************************ 50 If we have an access token, we can make requests, else we generate an authentication URL. 52 ************************************************/ 53 if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 54 $client->setAccessToken($_SESSION['access_token']); //6. setting the token every time if we have access_token; otherwise, we need to retrieve the token as this token is very important to verity the user. 55 } else { 56 $authUrl = $client->createAuthUrl(); //2. to createAuthUrl(); 57 } 59 /************************************************ 60 If we're signed in and have a request to shorten a URL, then we create a new URL object, set the unshortened URL, and call the 'insert' method on the 'url' resource. Note that we re-store the access_token bundle, just in case anything 61 changed during the request - the main thing that might happen here is the access token itself is refreshed if the application has offline access. 62 ************************************************/ 63 if ($client->getAccessToken() && isset($_GET['url'])) { //7. to check accessToke; we have a request to shorten a URL if signed in. 64 $url = new Google_Service_Urlshortener_Url(); 65 $url->longUrl = $_GET['url']; 66 $short = $service->url->insert($url); 67 $_SESSION['access_token'] = $client->getAccessToken(); 68 } 70 echo pageHeader("Getting Gmail"); 71 ?> 72 <div class="box" style="800px;"> 73 <div class="request"> 74 <?php 75 if (isset($authUrl)) { 76 echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>"; // 3. Go to gmail to login or verify. 77 } else { 79 $mail_list = listMessages($gmail_service, "me"); //8.Go to retrieve mail by "me" theme 80 echo "<a class='logout' href='?logout'>Logout</a>"; 81 } 82 ?> 83 </div> 85 <div class="mail_list" > 86 <?php 88 if (isset($mail_list)) { 90 $cnt=1; 91 //$num is the number to display how many incoming email. 92 $num = 10; 93 foreach($mail_list as $each_mail) { 94 echo "$cnt"; 95 if($cnt<=$num){ 96 $message = getMessage($gmail_service, 'me', $each_mail['id']); // 10. 99 echo "<pre>"; 100 // print_r($message); 101 echo "</pre>"; 104 $mail_payload = $message->getPayload(); 105 $mail_parts = $mail_payload->getParts(); 107 $mail_headers = $mail_payload->getHeaders(); 110 //extract headers in mail (to, from, subject, etc.) 111 // echo "<pre>"; 112 // var_dump($mail_headers); 113 // echo "</pre>"; 116 $mail_body_raw = $mail_payload['modelData']['parts'][0]['modelData']['body']['data']; //11. 118 $mail_body = base64_decode($mail_body_raw); //12. 119 $mail_body = str_replace(" ", "<br/>", $mail_body); 120 echo $mail_body; 122 } 123 $cnt++; 124 } 128 } 129 ?> 130 </div> 131 </div> 132 <?php 133 //echo pageFooter(__FILE__); 135 /** 136 * Get list of Messages in user's mailbox.138 * @param Google_Service_Gmail $service Authorized Gmail API instance. 139 * @param string $userId User's email address. The special value 'me' can be used to indicate the authenticated user. 141 * @return array Array of Messages. 142 */ 143 function listMessages($service, $userId) { 144 $pageToken = NULL; 145 $messages = array(); 146 $opt_param = array(); 147 do { 148 try { 149 if ($pageToken) { 150 $opt_param['pageToken'] = $pageToken; 151 } 152 $messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param); //9. 153 if ($messagesResponse->getMessages()) { 154 $messages = array_merge($messages, $messagesResponse->getMessages()); 155 $pageToken = $messagesResponse->getNextPageToken(); 156 } 157 } catch (Exception $e) { 158 print 'An error occurred: ' . $e->getMessage(); 159 } 160 } while ($pageToken); 162 foreach ($messages as $message) { 163 // print 'Message with ID: ' . $message->getId() . '<br/>'; 164 } 166 return $messages; 167 } 169 /** 170 * Get Message with given ID.172 * @param Google_Service_Gmail $service Authorized Gmail API instance. 173 * @param string $userId User's email address. The special value 'me'can be used to indicate the authenticated user. 175 * @param string $messageId ID of Message to get. 176 * @return Google_Service_Gmail_Message Message retrieved. 177 */ 178 function getMessage($service, $userId, $messageId) { 179 try { 180 $message = $service->users_messages->get($userId, $messageId); 181 // print 'Message with ID: ' . $message->getId() . ' retrieved.'; 182 return $message; 183 } catch (Exception $e) { 184 print 'An error occurred: ' . $e->getMessage(); 185 } 186 } 190 /** 191 * Send Message.193 * @param Google_Service_Gmail $service Authorized Gmail API instance. 194 * @param string $userId User's email address. The special value 'me' can be used to indicate the authenticated user. 196 * @param Google_Service_Gmail_Message $message Message to send. 197 * @return Google_Service_Gmail_Message sent Message. 198 */ 199 function sendMessage($service, $userId, $message) { 200 try { 201 $message = $service->users_messages->send($userId, $message); 202 print 'Message with ID: ' . $message->getId() . ' sent.'; 203 return $message; 204 } catch (Exception $e) { 205 print 'An error occurred: ' . $e->getMessage(); 206 } 207 }

    holder

  • 相关阅读:
    Promise简单使用,需要在ES6以上
    uni-app条件编译:#ifdef #ifndef #endif
    js获取年月日
    js验证手机号、身份证等
    json.stringify()与json.parse()
    Vuex基本使用的总结--转载
    ...mapMutations前面的三个点什么意思
    制作缩略图、远程缩略图
    node整个环境的启动
    redis命令
  • 原文地址:https://www.cnblogs.com/yeatschen/p/5421285.html
Copyright © 2011-2022 走看看