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="width: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("\n", "<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

时间: 2024-10-14 23:03:19

Google Mail in PHP的相关文章

Google Accounts,OpenID,OAuth

App Engine以与Google Accounts的集成为其特色.Google Accounts是被Google应用程序如:Google Mail.Google Docs.Google Calendar所使用的用户帐户系统.你可以使用Google Accounts作为你的应用的帐户系统,这样你就没有必要建立你自己的帐户系统.如果你的用户已经拥有了Google帐户,他们可以使用他们已有的帐户登录你的应用,而不需要仅仅为你的应用创建新的帐户. Google帐户对于使用Google Apps为你的

Python 批量获取Google用户动态 (分页)

CODE: #!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2014-9-7 @author: guaguastd @name: user_activity_loop.py ''' import json from login import google_api_request from html import cleanHtml import os MAX_RESULTS = 40 while True: query = raw

google host 配置

#google hosts 2015 by www.oicqzone.com #更新时间:2015年1月22日 14:16:05 #更新地址:http://www.oicqzone.com/pc/google-hosts.html #base services 64.233.169.103 google.com 64.233.169.103 www.google.com 64.233.169.103 m.google.com 64.233.169.103 scholar.google.com 6

Go语言(golang)开源项目大全

转http://www.open-open.com/lib/view/open1396063913278.html内容目录Astronomy构建工具缓存云计算命令行选项解析器命令行工具压缩配置文件解析器控制台用户界面加密数据处理数据结构数据库和存储开发工具分布式/网格计算文档编辑器Encodings and Character SetsGamesGISGo ImplementationsGraphics and AudioGUIs and Widget ToolkitsHardwareLangu

[转]掌握 Dojo 工具包,第 2 部分: XHR 框架与 Dojo

作者:secooler 快乐的DBA Ajax 的兴起改变了传统的 B/S 结构应用程序中以页面为单位的交互模式,Ajax 引入的局部刷新机制带来了更好的用户体验,促使浏览器中的页面开始向应用程序发展,Google Mail, Google Reader 是在这种趋势下诞生的典型应用. Dojo 提供了基于 XmlHttpRequest 的对象的 XHR 框架来支持异步 Ajax 调用,另外 Dojo.io 包中提供了两种浏览器与服务器交互的方式:iframe. 隐藏框架和 script. 动态

机器学习十大算法(二)

文章来源:https://www.dezyre.com/article/top-10-machine-learning-algorithms/202 本人自行翻译,如有错误,还请指出.后续会继续补充实例及代码实现. 3.机器学习算法概述 3.1 朴素贝叶斯分类器算法 手动分类网页,文档,电子邮件或任何其他冗长的文本注释将是困难且实际上不可能的. 这是朴素贝叶斯分类器机器学习算法来解决. 分类器是从可用类别之一分配总体的元素值的函数. 例如,垃圾邮件过滤是朴素贝叶斯分类器算法的流行应用程序. 此处

XHR 框架与 Dojo( xhrGet,xhrPut,xhrDelete)

总结 本文介绍了 Dojo 中三种浏览器与服务器交互的方式,这三种方式各有优缺点,但是在使用方式却出奇的一致: xhr 框架的函数,dojo.io.iframe.dojo.io.script 对象的函数使用的 JSON 对象参数也极其相似,而且浅显易懂. Dojo 设计者的这一良好设计极大的减轻了开发人员的学习负担,作为框架开发人员应该了解这一理念.表 2 对这三种方式从三个方面进行了比较.   支持的 HTTP 请求类型 期望的输出 跨域 XHR Get, post, delete, put

08 comet反向ajax

一:HTTP协议与技久链接+分块传输---->反向ajax 反向ajax又叫comet, server push,服务器推技术. 应用范围: 网页聊天服务器,, 新浪微博在线聊天,google mail 网页聊天,都有用到. 原理: 一般而言, HTTP协议的特点, 连接<->断开. 具体什么时间断开? 服务器响应content-length,收到到指定length长度的内容时,也就断开了. 在http1.1协议中, 允许你不写content-length ,比如要发送的内容长度确实不知

http协议与分块传输,持久连接及反向ajax

web QQ都用过吧,这涉及到哪些技术,有一个就是反向ajax. 反向ajax又叫comet,server push,服务器推技术. 应用范围: 网页聊天服务器,, 新浪微博在线聊天,google mail 网页聊天,都有用到. 原理: 一般而言, HTTP协议的特点, 连接<->断开. 具体什么时间断开? 服务器响应content-length,收到到指定length长度的内容时,也就断开了. 在http1.1协议中, 允许你不写content-length,比如要发送的内容长度确实不知道时