├── .gitignore ├── README.md ├── _config.yml ├── composer.json ├── composer.lock ├── examples ├── add_remove_labels.php ├── attachment.php ├── create_label.php ├── delete.php ├── includes │ ├── auth.php │ └── sample_config.php ├── label_details.php ├── labels.php ├── login.php ├── message_details.php ├── messages.php └── send.php └── src └── GmailWrapper ├── Authenticate.php └── Messages.php /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | examples/includes/config.php 3 | .DS_Store? 4 | .DS_Store 5 | */.DS_Store 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
Sponsored by
2 | 3 | 4 | # PHP Wrapper for Gmail API 5 | 6 | ## Description 7 | 8 | GmailPHP is a PHP wrapper that makes it easier to use the messaging API provided by Google. This library makes use of [PHPMailer](https://github.com/PHPMailer/PHPMailer) and [Google's PHP SDK V1](https://github.com/google/google-api-php-client/tree/v1-master). 9 | 10 | Installation: 11 | 12 | GmailPHP is available via [Composer/Packagist](https://packagist.org/packages/adevait/gmail-wrapper), so you can easily install it by adding the following line to your composer.json file 13 | 14 | ```"adevait/gmail-wrapper": "1.0.*"``` 15 | 16 | or executing the following in you command line. 17 | 18 | ```composer require adevait/gmail-wrapper``` 19 | 20 | Usage notes: 21 | 22 | In addition to the source code, example files with implementation of every function of this wrapper are added in the examples directory. Sample config file is also added, which content should be replaced with the real APP name, client details and developer key. 23 | 24 | Available functions: 25 | 26 | * Login (examples/login.php) 27 | * Send message (examples/send.php) 28 | * List messages (examples/messages.php) 29 | * View message (examples/message_details.php) 30 | * Delete message (examples/delete.php) 31 | * Add label (examples/add_remove_labels.php) 32 | * List labels (examples/labels.php) 33 | * Create label (examples/create_label.php) 34 | 35 | Additional functions that can be used similarly to the ones in the examples are removing a label, undoing a delete operation and creating a draft message. 36 | 37 | ## License 38 | 39 | GmailPHP is released under the MIT license 40 | 41 | ## Support 42 | 43 | Please direct any feedback to trajchevska@adevait.com 44 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-minimal -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "adevait/gmail-wrapper", 3 | "type": "library", 4 | "description": "A PHP client library that consumes Gmail APIs", 5 | "keywords": ["gmail","google","API"], 6 | "homepage": "https://github.com/adevait/GmailPHP", 7 | "license": "MIT", 8 | "authors": [ 9 | { 10 | "name": "Katerina Trajchevska", 11 | "email": "trajchevska@adevait.com", 12 | "role": "Developer" 13 | } 14 | ], 15 | "require": { 16 | "php": ">=5.3.3", 17 | "google/apiclient": "1.1.*@dev", 18 | "phpmailer/phpmailer": "~5.2" 19 | }, 20 | "autoload": { 21 | "psr-4": { 22 | "GmailWrapper\\": "src/GmailWrapper/" 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /composer.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_readme": [ 3 | "This file locks the dependencies of your project to a known state", 4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", 5 | "This file is @generated automatically" 6 | ], 7 | "hash": "4188c6ce6fbcb93d9cae460de83c57d5", 8 | "content-hash": "fdf54ee0ba16281fed61d85aa45e539a", 9 | "packages": [ 10 | { 11 | "name": "google/apiclient", 12 | "version": "1.1.7", 13 | "source": { 14 | "type": "git", 15 | "url": "https://github.com/google/google-api-php-client.git", 16 | "reference": "400f250a30ae1dd4c4a0a4f750fe973fc70e6311" 17 | }, 18 | "dist": { 19 | "type": "zip", 20 | "url": "https://api.github.com/repos/google/google-api-php-client/zipball/400f250a30ae1dd4c4a0a4f750fe973fc70e6311", 21 | "reference": "400f250a30ae1dd4c4a0a4f750fe973fc70e6311", 22 | "shasum": "" 23 | }, 24 | "require": { 25 | "php": ">=5.2.1" 26 | }, 27 | "require-dev": { 28 | "phpunit/phpunit": "3.7.*", 29 | "squizlabs/php_codesniffer": "~2.3" 30 | }, 31 | "type": "library", 32 | "extra": { 33 | "branch-alias": { 34 | "dev-master": "1.1.x-dev" 35 | } 36 | }, 37 | "autoload": { 38 | "classmap": [ 39 | "src/" 40 | ] 41 | }, 42 | "notification-url": "https://packagist.org/downloads/", 43 | "license": [ 44 | "Apache-2.0" 45 | ], 46 | "description": "Client library for Google APIs", 47 | "homepage": "http://developers.google.com/api-client-library/php", 48 | "keywords": [ 49 | "google" 50 | ], 51 | "time": "2016-02-02 18:50:42" 52 | }, 53 | { 54 | "name": "phpmailer/phpmailer", 55 | "version": "v5.2.15", 56 | "source": { 57 | "type": "git", 58 | "url": "https://github.com/PHPMailer/PHPMailer.git", 59 | "reference": "d0186171b28af4f06ac2ad8a84a8f3d6cbc3ba6c" 60 | }, 61 | "dist": { 62 | "type": "zip", 63 | "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/d0186171b28af4f06ac2ad8a84a8f3d6cbc3ba6c", 64 | "reference": "d0186171b28af4f06ac2ad8a84a8f3d6cbc3ba6c", 65 | "shasum": "" 66 | }, 67 | "require": { 68 | "php": ">=5.0.0" 69 | }, 70 | "require-dev": { 71 | "phpdocumentor/phpdocumentor": "*", 72 | "phpunit/phpunit": "4.7.*" 73 | }, 74 | "suggest": { 75 | "league/oauth2-google": "Needed for Google XOAUTH2 authentication" 76 | }, 77 | "type": "library", 78 | "autoload": { 79 | "classmap": [ 80 | "class.phpmailer.php", 81 | "class.phpmaileroauth.php", 82 | "class.phpmaileroauthgoogle.php", 83 | "class.smtp.php", 84 | "class.pop3.php", 85 | "extras/EasyPeasyICS.php", 86 | "extras/ntlm_sasl_client.php" 87 | ] 88 | }, 89 | "notification-url": "https://packagist.org/downloads/", 90 | "license": [ 91 | "LGPL-2.1" 92 | ], 93 | "authors": [ 94 | { 95 | "name": "Jim Jagielski", 96 | "email": "jimjag@gmail.com" 97 | }, 98 | { 99 | "name": "Marcus Bointon", 100 | "email": "phpmailer@synchromedia.co.uk" 101 | }, 102 | { 103 | "name": "Andy Prevost", 104 | "email": "codeworxtech@users.sourceforge.net" 105 | }, 106 | { 107 | "name": "Brent R. Matzelle" 108 | } 109 | ], 110 | "description": "PHPMailer is a full-featured email creation and transfer class for PHP", 111 | "time": "2016-05-10 18:39:36" 112 | } 113 | ], 114 | "packages-dev": [], 115 | "aliases": [], 116 | "minimum-stability": "stable", 117 | "stability-flags": { 118 | "google/apiclient": 20 119 | }, 120 | "prefer-stable": false, 121 | "prefer-lowest": false, 122 | "platform": { 123 | "php": ">=5.3.3" 124 | }, 125 | "platform-dev": [] 126 | } 127 | -------------------------------------------------------------------------------- /examples/add_remove_labels.php: -------------------------------------------------------------------------------- 1 | addRemoveLabels($_GET['messageId'],[],['Label_14']); -------------------------------------------------------------------------------- /examples/attachment.php: -------------------------------------------------------------------------------- 1 | getAttachment($_GET['messageId'],$_GET['part_id']); 14 | if(!$attachment['status']) { 15 | echo $attachment['message']; 16 | exit; 17 | } 18 | foreach ($attachment['data']['headers'] as $key => $value) { 19 | header($key.':'.$value); 20 | } 21 | echo $attachment['data']['data']; 22 | 23 | -------------------------------------------------------------------------------- /examples/create_label.php: -------------------------------------------------------------------------------- 1 | createLabel('Test Label'); -------------------------------------------------------------------------------- /examples/delete.php: -------------------------------------------------------------------------------- 1 | trash($_GET['messageId'])); -------------------------------------------------------------------------------- /examples/includes/auth.php: -------------------------------------------------------------------------------- 1 | isTokenValid($_SESSION['tokens'])) { 13 | if(!isset($_SESSION['tokens']->refresh_token)) { 14 | header('Location:login.php'); 15 | exit; 16 | } 17 | // If the app has offline access, refresh the access token automatically 18 | $response = $authenticate->refreshToken($_SESSION['tokens']->refresh_token); 19 | if(!$response['status']) { 20 | header('Location:login.php'); 21 | exit; 22 | } 23 | $_SESSION['tokens'] = $authenticate->getTokens(); 24 | } -------------------------------------------------------------------------------- /examples/includes/sample_config.php: -------------------------------------------------------------------------------- 1 | getLabelDetails($_GET['labelId']); 14 | if(!$label_details['status']) { 15 | echo $label_details['message'];exit; 16 | } 17 | $label_details = $label_details['data']; 18 | $label_name = $label_details->getName(); 19 | echo ''; 25 | var_dump($authenticate->getUserDetails()); 26 | } else { 27 | echo $auth['message']; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /examples/message_details.php: -------------------------------------------------------------------------------- 1 | getMessageDetails($_GET['messageId']); 14 | if(!$messageDetails['status']) { 15 | echo $messageDetails['message']; 16 | exit; 17 | } 18 | if (!empty($messageDetails['data'])) { 19 | header('Content-type:text/html; charset=utf-8'); 20 | foreach ($messageDetails['data']['headers'] as $key => $value) { 21 | echo '-------------------------------------------------------------------------------- /src/GmailWrapper/Authenticate.php: -------------------------------------------------------------------------------- 1 | is_authenticated = false; 24 | $this->client = new Google_Client(); 25 | $this->client_id = $clientID; 26 | $this->client->setClientId($clientID); 27 | $this->client->setClientSecret($clientSecret); 28 | $this->client->setApplicationName($applicationName); 29 | $this->client->setDeveloperKey($developerKey); 30 | $this->gmail = new Google_Service_Gmail($this->client); 31 | } 32 | 33 | /** 34 | * Returns the current instance of the Authenticate class if it already exists or creates a new one if not. 35 | * @param string $clientID The client id of the app 36 | * @param string $clientSecret The client secret key of the app 37 | * @param string $applicationName The application name 38 | * @param string $developerKey The developer key 39 | * @return Authenticate The instance of the Authenticate class 40 | */ 41 | public static function getInstance($clientID, $clientSecret, $applicationName, $developerKey) 42 | { 43 | if (null === static::$instance) { 44 | static::$instance = new Authenticate($clientID, $clientSecret, $applicationName, $developerKey); 45 | } 46 | return static::$instance; 47 | } 48 | 49 | /** 50 | * Returns the login url needed for user authentication 51 | * @param string $redirect_url The redirect url where the app should return after authentication 52 | * @param array $scopes The login scope - permissions requested from the user 53 | * @param string/boolean $accessType The access type (online or offline), online is default 54 | * @param string/boolean $approvalPrompt Whether to force approval on every login 55 | * @return array Status and data/error message depending on the success of the operation 56 | */ 57 | public function getLogInURL($redirect_url, $scopes = array('openid'), $accessType = false, $approvalPrompt = false) 58 | { 59 | try { 60 | $this->client->setRedirectUri($redirect_url); 61 | $this->client->setScopes($scopes); 62 | if ($accessType) { 63 | $this->client->setAccessType($accessType); 64 | } 65 | if($approvalPrompt) { 66 | $this->client->setApprovalPrompt($approvalPrompt); 67 | } 68 | $loginUrl = $this->client->createAuthUrl(); 69 | return ['status' => true, 'data' => $loginUrl]; 70 | } catch (\Google_Auth_Exception $e) { 71 | return ['status' => false, 'message' => $e->getMessage()]; 72 | } 73 | } 74 | 75 | /** 76 | * Login logic 77 | * @return array Status and message depending on the success of the operation 78 | */ 79 | public function logIn($code) 80 | { 81 | try { 82 | $this->client->authenticate($code); 83 | $tokens = $this->client->getAccessToken(); 84 | $this->tokens = json_decode($tokens); 85 | $attributes = $this->client->verifyIdToken($this->tokens->id_token, $this->client_id)->getAttributes(); 86 | if ($attributes) { 87 | $this->is_authenticated = true; 88 | $this->user_id = $attributes['payload']['sub']; 89 | return ['status' => true, 'message' => 'Successfully authenticated.']; 90 | } 91 | return ['status' => false, 'message' => 'Error. Please try again.']; 92 | } catch (\Google_Auth_Exception $e) { 93 | return ['status' => false, 'message' => $e->getMessage()]; 94 | } 95 | } 96 | 97 | /** 98 | * Check whether the current token is still valid 99 | * @param object $tokens The tokens as returned by Google's API 100 | * @return array Status and message depending on the token validity 101 | */ 102 | public function isTokenValid($tokens) 103 | { 104 | try { 105 | $this->client->setAccessToken(json_encode($tokens)); 106 | if (!$this->client->isAccessTokenExpired()) { 107 | $this->tokens = $tokens; 108 | $attributes = $this->client->verifyIdToken($this->tokens->id_token, $this->client_id)->getAttributes(); 109 | if ($attributes) { 110 | $this->is_authenticated = true; 111 | $this->user_id = $attributes['payload']['sub']; 112 | return ['status' => true, 'message' => 'Token is valid.']; 113 | } 114 | return ['status' => false, 'message' => 'Error. Please try again.']; 115 | } 116 | } catch (\Google_Auth_Exception $e) { 117 | return ['status' => false, 'message' => $e->getMessage()]; 118 | } 119 | } 120 | 121 | /** 122 | * Get the details of the logged in user 123 | * @return array Status and data/error message depending on the success of the operation 124 | */ 125 | public function getUserDetails() 126 | { 127 | if ($this->is_authenticated) { 128 | try { 129 | $me = $this->gmail->users->getProfile('me'); 130 | return [ 131 | 'user_id' => $this->user_id, 132 | 'email' => $me['emailAddress'] 133 | ]; 134 | } catch (\Google_Service_Exception $e) { 135 | return ['status' => false, 'message' => $e->getMessage()]; 136 | } 137 | } 138 | return ['status' => false, 'message' => 'User is not authenticated.']; 139 | } 140 | 141 | /** 142 | * Refreshes the access token 143 | * @param string $refreshToken Refresh token returned by Google's API 144 | * @return array Status and error message if the operation is unsuccessful 145 | */ 146 | public function refreshToken($refreshToken) 147 | { 148 | try { 149 | $this->client->refreshToken($refreshToken); 150 | $this->tokens = json_decode($this->client->getAccessToken()); 151 | $this->tokens->refresh_token = $refreshToken; 152 | $attributes = $this->client->verifyIdToken($this->tokens->id_token, $this->client_id)->getAttributes(); 153 | if ($attributes) { 154 | $this->is_authenticated = true; 155 | $this->user_id = $attributes['payload']['sub']; 156 | return ['status' => true]; 157 | } 158 | return ['status' => false, 'message' => 'Token is invalid.']; 159 | } catch (\Google_Auth_Exception $e) { 160 | return ['status' => false, 'message' => $e->getMessage()]; 161 | } 162 | } 163 | 164 | /** 165 | * Returns the id of the logged in user 166 | * @return string The id of the logged in user 167 | */ 168 | public function getUserId() 169 | { 170 | if(!$this->user_id) { 171 | throw new \Exception("User is not authenticated", 1); 172 | } 173 | return $this->user_id; 174 | } 175 | 176 | /** 177 | * Returns the google client 178 | * @return Google_Client The google client 179 | */ 180 | public function getClient() 181 | { 182 | return $this->client; 183 | } 184 | 185 | /** 186 | * Returns the saved tokens 187 | * @return object Tokens as returned by Google 188 | */ 189 | public function getTokens() 190 | { 191 | return $this->tokens; 192 | } 193 | 194 | /** 195 | * Returns the status of the user authentication 196 | * @return boolean Status variable that shows whether the user is authenticated 197 | */ 198 | public function isAuthenticated() 199 | { 200 | return $this->is_authenticated; 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /src/GmailWrapper/Messages.php: -------------------------------------------------------------------------------- 1 | authenticate = $authenticate; 26 | } 27 | 28 | /** 29 | * Get a list of all messages of the authenticated user 30 | * @param string $filter Filtering query options, as used in gmail client 31 | * @param string $PageToken The page identifier - messages are loaded page by page to avoid overload 32 | * @return array Status and data/error message depending on the success of the operation 33 | */ 34 | public function getMessages($optParams = array(), $pageToken = false) 35 | { 36 | try { 37 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 38 | $messages = []; 39 | if ($pageToken) { 40 | $optParams['pageToken'] = $pageToken; 41 | } 42 | $messagesResponse = $gmail->users_messages->listUsersMessages($this->authenticate->getUserId(), $optParams); 43 | if ($messagesResponse->getMessages()) { 44 | $messages = array_merge($messages, $messagesResponse->getMessages()); 45 | $nextPageToken = $messagesResponse->getNextPageToken(); 46 | return ['status' => true, 'data' => $messages, 'nextToken' => $nextPageToken]; 47 | } 48 | } catch (\Google_Service_Exception $e) { 49 | return ['status' => false, 'message' => $e->getMessage()]; 50 | } catch(\Google_Exception $e) { 51 | return ['status' => false, 'message' => $e->getMessage()]; 52 | } catch(\Exception $e) { 53 | return ['status' => false, 'message' => $e->getMessage()]; 54 | } 55 | } 56 | 57 | /** 58 | * Returns the details for a selected message 59 | * @param string $messageId The id of the message 60 | * @return array Status and data/error message depending on the success of the operation 61 | */ 62 | public function getMessageDetails($messageId) 63 | { 64 | try { 65 | $optParam = []; 66 | $data = []; 67 | $headers = []; 68 | $body = ['text/plain' => [], 'text/html' => []]; 69 | $files = []; 70 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 71 | $message = $gmail->users_messages->get($this->authenticate->getUserId(), $messageId, $optParam); 72 | $messageDetails = $message->getPayload(); 73 | foreach ($messageDetails['headers'] as $item) { 74 | $headers[$item->name] = $item->value; 75 | } 76 | $data['headers'] = $headers; 77 | if (!is_null($messageDetails['body']['data'])) { 78 | array_push($body['text/plain'], nl2br($this->base64UrlDecode($messageDetails['body']['data']))); 79 | } 80 | foreach ($messageDetails['parts'] as $key => $value) { 81 | if (isset($value['body']['data'])) { 82 | array_push($body[$value['mimeType']], nl2br($this->base64UrlDecode($value['body']['data']))); 83 | } else { 84 | array_push($files, $value['partId']); 85 | } 86 | } 87 | $data['body'] = $body; 88 | $data['threadId'] = $message->getThreadId(); 89 | $data['labelIds'] = $message->getLabelIds(); 90 | $data['snippet'] = $message->getSnippet(); 91 | $data['files'] = $files; 92 | return ['status' => true, 'data' => $data]; 93 | } catch (\Google_Service_Exception $e) { 94 | return ['status' => false, 'message' => $e->getMessage()]; 95 | } catch(\Google_Exception $e) { 96 | return ['status' => false, 'message' => $e->getMessage()]; 97 | } catch(\Exception $e) { 98 | return ['status' => false, 'message' => $e->getMessage()]; 99 | } 100 | } 101 | 102 | /** 103 | * Returns the detailed attachment data 104 | * @param string $messageId The id of the message 105 | * @param int $partId The id of the part of the given message, that references the selected attachment 106 | * @return array Status and data/error message depending on the success of the operation 107 | */ 108 | public function getAttachment($messageId, $partId) 109 | { 110 | try { 111 | $files = []; 112 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 113 | $attachmentDetails = $this->getAttachmentDetailsFromMessage($messageId, $partId); 114 | if (!$attachmentDetails['status']) { 115 | return $attachmentDetails; 116 | } 117 | $attachment = $gmail->users_messages_attachments->get($this->authenticate->getUserId(), $messageId, $attachmentDetails['attachmentId']); 118 | $attachmentDetails['data'] = $this->base64UrlDecode($attachment->data); 119 | return ['status' => true, 'data' => $attachmentDetails]; 120 | } catch (\Google_Service_Exception $e) { 121 | return ['status' => false, 'message' => $e->getMessage()]; 122 | } catch(\Google_Exception $e) { 123 | return ['status' => false, 'message' => $e->getMessage()]; 124 | } catch(\Exception $e) { 125 | return ['status' => false, 'message' => $e->getMessage()]; 126 | } 127 | } 128 | 129 | /** 130 | * Returns the attachments details from the message data, so a downloadable file can be created 131 | * @param string $messageId The id of the message 132 | * @param int $partId The id of the part of the given message, that references the selected attachment 133 | * @return array Status and data/error message depending on the success of the operation 134 | */ 135 | private function getAttachmentDetailsFromMessage($messageId, $partId) 136 | { 137 | try { 138 | $attachmentHeaders = []; 139 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 140 | $message = $gmail->users_messages->get($this->authenticate->getUserId(), $messageId); 141 | $messageDetails = $message->getPayload(); 142 | foreach ($messageDetails['parts'][$partId]['headers'] as $item) { 143 | $attachmentHeaders[$item->name] = $item->value; 144 | } 145 | return ['status' => true, 'mimeType' => $messageDetails['parts'][$partId]['mimeType'], 'filename' => $messageDetails['parts'][$partId]['filename'] ,'headers' => $attachmentHeaders, 'attachmentId' => $messageDetails['parts'][$partId]['body']['attachmentId']]; 146 | } catch (\Google_Service_Exception $e) { 147 | return ['status' => false, 'message' => $e->getMessage()]; 148 | } catch(\Google_Exception $e) { 149 | return ['status' => false, 'message' => $e->getMessage()]; 150 | } catch(\Exception $e) { 151 | return ['status' => false, 'message' => $e->getMessage()]; 152 | } 153 | } 154 | 155 | /** 156 | * Prepares the email and sends it using Google_Service_Gmail_Message 157 | * @param string $to Email address to which the message should be sent 158 | * @param string $subject The subject of the email 159 | * @param string $body The body of the email 160 | * @param array $attachment An array with name and tmp_name (in the exact order) parameters for every attachment that should be uploaded 161 | * @param string $threadId The id of the thread if the message is a reply to a recieved message, false otherwise 162 | * @return array Status and data/error message depending on the success of the operation 163 | */ 164 | public function send($to, $subject, $body, $attachment = array(), $threadId = false) 165 | { 166 | try { 167 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 168 | $message = new Google_Service_Gmail_Message(); 169 | $userId = $this->authenticate->getUserId(); 170 | $this->createMessage($gmail, $message, $userId, $to, $subject, $body, $attachment, $threadId); 171 | $response = $gmail->users_messages->send($userId, $message); 172 | return ['status' => true, 'data' => $response]; 173 | } catch (\Google_Service_Exception $e) { 174 | return ['status' => false, 'message' => $e->getMessage()]; 175 | } catch(\Google_Exception $e) { 176 | return ['status' => false, 'message' => $e->getMessage()]; 177 | } catch(\Exception $e) { 178 | return ['status' => false, 'message' => $e->getMessage()]; 179 | } 180 | } 181 | 182 | /** 183 | * Creates a draft message 184 | * @param string $to Email address of the recepient 185 | * @param string $subject Subject of the message 186 | * @param string $body The message body 187 | * @param array $attachment An array with name and tmp_name (in the exact order) parameters for every attachment that should be uploaded 188 | * @param string $threadId The id of the thread if the message is a reply to a recieved message, false otherwise 189 | * @return array Status and data/error message depending on the success of the operation 190 | */ 191 | public function createDraft($to, $subject, $body, $attachment = array(), $threadId = false) 192 | { 193 | try { 194 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 195 | $message = new Google_Service_Gmail_Message(); 196 | $userId = $this->authenticate->getUserId(); 197 | $this->createMessage($gmail, $message, $userId, $to, $subject, $body, $attachment, $threadId); 198 | $draft = new Google_Service_Gmail_Draft(); 199 | $draft->setMessage($message); 200 | $response = $gmail->users_drafts->create($userId, $draft); 201 | return ['status' => true, 'data' => $response]; 202 | } catch (\Google_Service_Exception $e) { 203 | return ['status' => false, 'message' => $e->getMessage()]; 204 | } catch(\Google_Exception $e) { 205 | return ['status' => false, 'message' => $e->getMessage()]; 206 | } catch(\Exception $e) { 207 | return ['status' => false, 'message' => $e->getMessage()]; 208 | } 209 | } 210 | 211 | 212 | /** 213 | * Helper function used for creating a message structure to use when sending a message or creating a draft 214 | * @param Google_Service_Gmail &$gmail Instance of the gmail service 215 | * @param Google_Service_Gmail_Message &$message Instance of the gmail message 216 | * @param string $userId Id of the user 217 | * @param string $to Email address of the recepient 218 | * @param string $subject Subject of the message 219 | * @param string $body The message body 220 | * @param array $attachment An array with name and tmp_name (in the exact order) parameters for every attachment that should be uploaded 221 | * @param string $threadId The id of the thread if the message is a reply to a recieved message, false otherwise 222 | */ 223 | private function createMessage(Google_Service_Gmail &$gmail, Google_Service_Gmail_Message &$message, $userId, $to, $subject, $body, $attachment = array(), $threadId = false) 224 | { 225 | $optParam = array(); 226 | $referenceId = ''; 227 | if ($threadId) { 228 | $thread = $gmail->users_threads->get($userId, $threadId); 229 | // If the message should be added in the same thread, override the sent subject and use the one from the thread 230 | if ($thread) { 231 | $optParam['threadId'] = $threadId; 232 | $threadMessages = $thread->getMessages($optParam); 233 | if ($threadMessages) { 234 | $messageId = $threadMessages[0]->getId(); 235 | $messageDetails = $this->getMessageDetails($messageId); 236 | $messageDetails = $messageDetails['data']; 237 | $subject = $messageDetails['headers']['Subject']; 238 | $referenceId = $messageDetails['headers']['Message-Id']; 239 | } 240 | } 241 | } 242 | $mail = new PHPMailer(); 243 | $user = $this->authenticate->getUserDetails(); 244 | $mail->CharSet = 'UTF-8'; 245 | $mail->From = $user['email']; 246 | $mail->FromName = $user['email']; 247 | $mail->addAddress($to); 248 | $mail->Subject = $subject; 249 | $mail->Body = $body; 250 | // set this dinamically 251 | $mail->IsHTML(true); 252 | if (!empty($attachment)) { 253 | foreach ($attachment as $key => $value) { 254 | $attachmentParams = array_combine(['name', 'tmpName'], $value); 255 | $mail->addAttachment($attachmentParams['tmpName'], $attachmentParams['name']); 256 | } 257 | } 258 | $mail->preSend(); 259 | $mime = $mail->getSentMIMEMessage(); 260 | $raw = $this->Base64UrlEncode($mime); 261 | $message->setRaw($raw); 262 | if ($threadId) { 263 | $message->setThreadId($threadId); 264 | } 265 | } 266 | 267 | /** 268 | * Deletes a message 269 | * @param string $messageId The id of the message that needs to be deleted 270 | * @return array Status and data/error message depending on the success of the operation 271 | */ 272 | public function trash($messageId) 273 | { 274 | try { 275 | $optParam = array(); 276 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 277 | return ['status' => true, 'data' => $gmail->users_messages->trash($this->authenticate->getUserId(), $messageId)]; 278 | } catch (\Google_Service_Exception $e) { 279 | return ['status' => false, 'message' => $e->getMessage()]; 280 | } catch(\Google_Exception $e) { 281 | return ['status' => false, 'message' => $e->getMessage()]; 282 | } catch(\Exception $e) { 283 | return ['status' => false, 'message' => $e->getMessage()]; 284 | } 285 | } 286 | 287 | /** 288 | * Undos a delete operation 289 | * @param string $messageId The id of the deleted message that needs to be retrieved 290 | * @return array Status and data/error message depending on the success of the operation 291 | */ 292 | public function untrash($messageId) 293 | { 294 | try { 295 | $optParam = array(); 296 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 297 | return ['status' => true, 'data' => $gmail->users_messages->untrash($this->authenticate->getUserId(), $messageId)]; 298 | } catch (\Google_Service_Exception $e) { 299 | return ['status' => false, 'message' => $e->getMessage()]; 300 | } catch(\Google_Exception $e) { 301 | return ['status' => false, 'message' => $e->getMessage()]; 302 | } catch(\Exception $e) { 303 | return ['status' => false, 'message' => $e->getMessage()]; 304 | } 305 | } 306 | 307 | /** 308 | * Returns a list of all labels 309 | * @return array Status and data/error message depending on the success of the operation 310 | */ 311 | public function getLabels() 312 | { 313 | try { 314 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 315 | $labelsResponse = $gmail->users_labels->listUsersLabels($this->authenticate->getUserId()); 316 | $labels = $labelsResponse->getLabels(); 317 | return ['status' => true, 'data' => $labels]; 318 | } catch (\Google_Service_Exception $e) { 319 | return ['status' => false, 'message' => $e->getMessage()]; 320 | } catch(\Google_Exception $e) { 321 | return ['status' => false, 'message' => $e->getMessage()]; 322 | } catch(\Exception $e) { 323 | return ['status' => false, 'message' => $e->getMessage()]; 324 | } 325 | } 326 | 327 | /** 328 | * Returns the details for a given label 329 | * @param string $labelId Id of the selected label 330 | * @return array Status and data/message depending on the success of the operation 331 | */ 332 | public function getLabelDetails($labelId) 333 | { 334 | try { 335 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 336 | $label = $gmail->users_labels->get($this->authenticate->getUserId(), $labelId); 337 | return ['status' => true, 'data' => $label]; 338 | } catch (\Google_Service_Exception $e) { 339 | return ['status' => false, 'message' => $e->getMessage()]; 340 | } catch(\Google_Exception $e) { 341 | return ['status' => false, 'message' => $e->getMessage()]; 342 | } catch(\Exception $e) { 343 | return ['status' => false, 'message' => $e->getMessage()]; 344 | } 345 | } 346 | 347 | /** 348 | * Creates a new label 349 | * @param string $name Name of the label 350 | * @return array Status and data/error message depending on the success of the operation 351 | */ 352 | public function createLabel($name) 353 | { 354 | try { 355 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 356 | $label = new Google_Service_Gmail_Label(); 357 | $label->setName($name); 358 | $response = $gmail->users_labels->create($this->authenticate->getUserId(), $label); 359 | return ['status' => true, 'data' => $response]; 360 | } catch (\Google_Service_Exception $e) { 361 | return ['status' => false, 'message' => $e->getMessage()]; 362 | } catch(\Google_Exception $e) { 363 | return ['status' => false, 'message' => $e->getMessage()]; 364 | } catch(\Exception $e) { 365 | return ['status' => false, 'message' => $e->getMessage()]; 366 | } 367 | } 368 | 369 | /** 370 | * Adds/Removes label from the given message 371 | * @param string $messageId The id of the message 372 | * @param array $addIds Ids of the labels to be added 373 | * @param array $removeIds Ids of the labels to be removed 374 | * @return array Status and data/error message depending on the success of the operation 375 | */ 376 | public function addRemoveLabels($messageId, $addIds = array(), $removeIds = array()) 377 | { 378 | try { 379 | $gmail = new Google_Service_Gmail($this->authenticate->getClient()); 380 | $modifyMessageRequest = new Google_Service_Gmail_ModifyMessageRequest(); 381 | if (!empty($addIds)) { 382 | $modifyMessageRequest->setAddLabelIds($addIds); 383 | } 384 | if (!empty($removeIds)) { 385 | $modifyMessageRequest->setRemoveLabelIds($removeIds); 386 | } 387 | $response = $gmail->users_messages->modify($this->authenticate->getUserId(), $messageId, $modifyMessageRequest); 388 | return ['status' => true, 'data' => $response]; 389 | } catch (\Google_Service_Exception $e) { 390 | return ['status' => false, 'message' => $e->getMessage()]; 391 | } catch(\Google_Exception $e) { 392 | return ['status' => false, 'message' => $e->getMessage()]; 393 | } catch(\Exception $e) { 394 | return ['status' => false, 'message' => $e->getMessage()]; 395 | } 396 | } 397 | 398 | /** 399 | * Returns a base64 decoded web safe string 400 | * @param String $string The string to be decoded 401 | * @return string Decoded string 402 | */ 403 | private function base64UrlDecode($string) 404 | { 405 | return base64_decode(str_replace(array('-', '_'), array('+', '/'), $string)); 406 | } 407 | 408 | /** 409 | * Returns a web safe base64 encoded string, used for encoding 410 | * @param String $string The string to be encoded 411 | * @return String Encoded string 412 | */ 413 | private function Base64UrlEncode($string) 414 | { 415 | return rtrim(strtr(base64_encode($string), '+/', '-_'), '='); 416 | } 417 | } 418 | --------------------------------------------------------------------------------'.$key.': '.$value.'
'; 22 | } 23 | echo 'Reply
'; 24 | echo 'Add label
'; 25 | echo 'Text/Plain
'; 26 | foreach ($messageDetails['data']['body']['text/plain'] as $key => $value) { 27 | echo $value.'
'; 28 | } 29 | echo 'Text/HTML
'; 30 | foreach ($messageDetails['data']['body']['text/html'] as $key => $value) { 31 | echo $value.'
'; 32 | } 33 | if(!empty($messageDetails['data']['files'])) { 34 | foreach ($messageDetails['data']['files'] as $key => $value) { 35 | echo 'Attachment '.($key+1).'
'; 36 | } 37 | } 38 | } else { 39 | echo 'No details retrieved'; 40 | } 41 | -------------------------------------------------------------------------------- /examples/messages.php: -------------------------------------------------------------------------------- 1 | getMessages([], $pageToken); 11 | if(!$messageList['status']) { 12 | echo $messageList['message']; 13 | exit; 14 | } 15 | foreach ($messageList['data'] as $key => $value) { 16 | $msgId = $value->getId(); 17 | echo ''.$msgId.'
'; 18 | } 19 | $nextToken = $messageList['nextToken']; 20 | echo ''; 21 | -------------------------------------------------------------------------------- /examples/send.php: -------------------------------------------------------------------------------- 1 | '.($i+1).' File too large.'; 22 | break; 23 | case UPLOAD_ERR_PARTIAL: 24 | $error_message .= ''.($i+1).' File upload was not completed.
'; 25 | break; 26 | case UPLOAD_ERR_NO_FILE: 27 | $error_message .= ''.($i+1).' Zero-length file uploaded.
'; 28 | break; 29 | default: 30 | $error_message .= ''.($i+1).' Internal error #'.$_FILES['attachment']['error'][$i].'
'; 31 | break; 32 | } 33 | if($error_message) { 34 | echo $error_message; 35 | exit; 36 | } 37 | } 38 | } 39 | $send = $message->send($_POST['email'],$_POST['subject'],$_POST['body'],$attachments,$thread); 40 | if(!$send['status']) { 41 | echo $send['message']; 42 | exit; 43 | } 44 | echo 'Message sent. See details below.
'; 45 | echo ''; 46 | var_dump($send['data']);exit; 47 | } 48 | ?> 49 | 56 |