2017 © Pedro Peláez
 

library laravel-gmail

Gmail API package for Laravel

image

dacastro4/laravel-gmail

Gmail API package for Laravel

  • Sunday, July 22, 2018
  • by dacastro4
  • Repository
  • 5 Watchers
  • 14 Stars
  • 830 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 4 Forks
  • 3 Open issues
  • 22 Versions
  • 137 % Grown

The README.md

Laravel Gmail

Build Status Scrutinizer Code Quality GitHub issues Total Downloads Monthly Downloads GitHub license, (*1)

Gmail

Gmail API for Laravel 9, (*2)

You need to create an application in the Google Console. Guidance here., (*3)

if you need Laravel 5 compatibility please use version 2.0.x. if you need Laravel 6 compatibility please use version 3.0.x. if you need Laravel 7 compatibility please use version 4.0.x. if you need Laravel 8 compatibility please use version 5.0.x., (*4)

Requirements

  • PHP ^8.0
  • Laravel 9

Installation

Add dacastro4/laravel-gmail to composer.json., (*5)

"dacastro4/laravel-gmail": "^6.1", (*6)

Run composer update to pull down the latest version., (*7)

Or run, (*8)

composer require dacastro4/laravel-gmail, (*9)

Now open up config/app.php and add the service provider to your providers array., (*10)

``` php 'providers' => [ Dacastro4\LaravelGmail\LaravelGmailServiceProvider::class, ], (*11)


Now add the alias. ``` php 'aliases' => [ 'LaravelGmail' => Dacastro4\LaravelGmail\Facade\LaravelGmail::class, ]

For laravel >=5.5 that's all. This package supports Laravel new Package Discovery., (*12)

For <= PHP 7.4 compatibility use version v5.0, (*13)

Migration from 5.0 to 6.0

Requires Laravel 9 and you have to change the dependency to "laravel/laravel": "^9.0" Please, follow Upgrading To 9.0 From 8.x Guide, (*14)

Migration from 4.0 to 5.0

Requires Laravel 8 and you have to change the dependency to "laravel/laravel": "^8.0" Please, follow Upgrading To 8.0 From 7.x Guide, (*15)

Migration from 3.0 to 4.0

Requires Laravel 7 and you have to change the dependency to "laravel/laravel": "^7.0" Please, follow Upgrading To 7.0 From 6.x Guide, (*16)

Migration from 2.0 to 3.0

Requires Laravel 6 and you only have to change the dependency to "laravel/laravel": "^6.0", (*17)

Migration from 1.0 to 2.0

The only changed made was the multi credentials feature. - Change your composer.json from "dacastro4/laravel-gmail": "^1.0" to "dacastro4/laravel-gmail": "^2.0", (*18)

I had to change version because of a typo and that might break apps calling those attributes., (*19)

All variable with the word "threat" was change to "thread" (yeah, I know.. sorry) Ex:, (*20)

Mail Class $threatId => $threadId, (*21)

Replyable Class $mail->setReplyThreat() => $mail->setReplyThread(), (*22)

and so on., (*23)

Migration from 0.6 to 1.0

The only changed made was the multi credentials feature. - Change your composer.json from "dacastro4/laravel-gmail": "^0.6" to "dacastro4/laravel-gmail": "^1.0", (*24)

If you don't want the multi user credentials, you don't have to do anything else, if you do, you're going to have to login again to create a new credentials file per user., (*25)

Configuration

You only have to set the following variables on your .env file and you'll be on your way:, (*26)

``` dotenv GOOGLE_PROJECT_ID= GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= GOOGLE_REDIRECT_URI= GOOGLE_ALLOW_MULTIPLE_CREDENTIALS GOOGLE_ALLOW_JSON_ENCRYPT, (*27)


To modify the scopes and the credentials file name, just run: Run `php artisan vendor:publish --provider="Dacastro4\LaravelGmail\LaravelGmailServiceProvider"` and modify the config file `config/gmail.php`. ### Allow multi user credentials To allow multi user credentials change `allow_multiple_credentials` to `true` in your config file or set the .env variable `GOOGLE_ALLOW_MULTIPLE_CREDENTIALS` to true if you're not using the config file. ### Allow encryption for json files To allow encryption for json files change `allow_json_encrypt` to `true` in your config file or set the .env variable `GOOGLE_ALLOW_JSON_ENCRYPT` to true if you're not using the config file. ### Available Scopes * all *(this one doesn't exists on Gmail Scopes, I added it.)* * compose * insert * labels * metadata * modify * readonly * send * settings_basic * settings_sharing [More about Gmail API scopes](https://developers.google.com/gmail/api/auth/scopes) Note: To change the scopes, users have to logout and login again. #### Additional Scopes If for some reason you need to add additional scopes. Add additional scopes in URL Style in config/gmail.php

'additional_scopes' => [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/documents', 'https://www.googleapis.com/auth/spreadsheets' ],, (*28)



# Example ## Welcome Blade: ```blade <body> <h1>{{ LaravelGmail::user() }}</h1> @if(LaravelGmail::check()) <a href="{{ url('oauth/gmail/logout') }}">logout</a> @else <a href="{{ url('oauth/gmail') }}">login</a> @endif </body>

Routes:

Route::get('/oauth/gmail', function (){
    return LaravelGmail::redirect();
});

Route::get('/oauth/gmail/callback', function (){
    LaravelGmail::makeToken();
    return redirect()->to('/');
});

Route::get('/oauth/gmail/logout', function (){
    LaravelGmail::logout(); //It returns exception if fails
    return redirect()->to('/');
});

Then if in your controller or wherever you want to do your logic, you do something like:, (*29)

$messages = LaravelGmail::message()->subject('test')->unread()->preload()->all();
foreach ( $messages as $message ) {
    $body = $message->getHtmlBody();
    $subject = $message->getSubject();
}

Note that if you don't preload the messages you have to do something like: $body = $message->load()->getSubject(); and after that you don't have to call it again., (*30)

Pagination

Use $messages->hasNextPage() to check whether next page is available. Use $messages->next() to get the next page results, which uses the same parameters (result per page, filters, etc.) when you loaded the first page. Use $messages->getPageToken() to get the unique identifier for the next page token. This is useful in creating a unique idendifier when storing the result in cache. Generally speaking, it is a bad practice to use API for pagination. It is slow and costly. Therefore, it is recommended to retrieve the cached result moving between pages and only flush the cache when have to., (*31)

Documentation

Basic

LaravelGmail::getAuthUrl Gets the URL to auth the user., (*32)

LaravelGmail::redirect You can use this as a direct method <a href="{{ LaravelGmail::redirect() }}">Login</a>, (*33)

LaravelGmail::makeToken() Set and Save AccessToken in json file (useful in the callback), (*34)

LaravelGmail::logout Logs out the user, (*35)

LaravelGmail::check Checks if the user is logged in, (*36)

LaravelGmail::setUserId($account_id)->makeToken() Set and Save AccessToken for $account_id (added v5.1.2), (*37)

Sending

use Dacastro4\LaravelGmail\Services\Message\Mail;

...

$mail = new Mail;

For to, from, cc and bcc, you can set an array of emails and name or a string of email and name., (*38)

$mail->using( $token ) If you don't want to use the token file, you can use this function that sets the token to use in the request. It doesn't refresh, (*39)

$mail->to( $to, $name = null ) sets the recipient email and name as optional, (*40)

$mail->from( $from, $name = null ) sets sender's email, (*41)

$mail->cc( $cc, $name = null ) sets carbon copy, (*42)

$mail->bcc( $bcc, $name = null ) sets a blind carbon copy, (*43)

$mail->subject( $subject ) sets the subject of the email, (*44)

$mail->message( $message ) sets the body of the email, (*45)

$mail->view( 'view.name', $dataArray ) sets the body from a blade file, (*46)

$mail->markdown( 'view.name', $dataArray ) sets the body from a markdown file, (*47)

$mail->attach( ...$path ) add file attachments to the email, (*48)

$mail->priority( $priority ) sets the priority of the email from 1 to 5, (*49)

$mail->reply() replies to an existent email, (*50)

$mail->send() sends a new email, (*51)

$mail->setHeader( $header, $value ) sets header to the email, (*52)

Mail

$mail->getId returns the email's ID, (*53)

$mail->getInternalDate returns date in UNIX format, (*54)

$mail->getDate returns a Carbon date from the header of the email, (*55)

$mail->getLabels returns an array of all the labels of the email, (*56)

$mail->getHeaders returns a collection of the header. Each header is an array with two rows key and value, (*57)

$mail->getSubject returns an string of the subject, (*58)

$mail->getFrom Returns an array with name and email of sender, (*59)

$mail->getFromName Returns string of name, (*60)

$mail->getFromEmail Returns string of email, (*61)

$mail->getTo Returns an array with name and email of all recipients, (*62)

$mail->getDeliveredTo Returns the email of the receiver, (*63)

$mail->getPlainTextBody Returns the plain text version of the email, (*64)

$mail->getRawPlainTextBody Returns the raw version of the body base64 encrypted, (*65)

$mail->hasAttachments Returns a boolean if the email has attachments, (*66)

$mail->load Load all the information of the email (labels, body, headers). You call this function on a single email. To load from the beginning see preload(), (*67)

$mail->getHeader( $headerName, $regex = null ) Returns the header by name. Optionally, you can execute a regex on the value, (*68)

Labels

$mail->markAsRead Removes the 'UNREAD' label from the email., (*69)

$mail->markAsUnread Adds the 'UNREAD' label to the email., (*70)

$mail->markAsImportant Adds the 'IMPORTANT' label to the email., (*71)

$mail->markAsNotImportant Removes the 'IMPORTANT' label from the email., (*72)

$mail->addStar Adds the 'STARRED' label to the email., (*73)

$mail->removeStar Removes the 'STARRED' label from the email., (*74)

$mail->sendToTrash Adds the 'TRASH' label to the email., (*75)

$mail->removeFromTrash Removes the 'TRASH' label from the email., (*76)

$mail->addLabel($string|$array) Add multiple or single label to the email, (*77)

$mail->removeLabel($string|$array) Removes multiple or single label from the email, (*78)

$mail->getAttachments() Get a collection of all the attachments on the email, (*79)

$mail->getAttachmentsWithData() Get a collection of all the attachments on the email including the data, (*80)

Listing: List all the labels of the email, (*81)

https://developers.google.com/gmail/api/reference/rest/v1/users.labels/list, (*82)

Example:, (*83)

``` php $mailbox = new LaravelGmailClass(config(), $account->id); $labels = $mailbox->labelsList($userEmail);, (*84)


`Create`: Create new label on the email with the labelName https://developers.google.com/gmail/api/reference/rest/v1/users.labels/create Example: ``` php $mailbox = new LaravelGmailClass(config(), LaravelGmail::user()); $label = new \Google_Service_Gmail_Label($this); $label->setMessageListVisibility('show'); `show || hide` $label->setLabelListVisibility('labelShow'); `labelShow || labelShowIfUnread || labelHide` $label->setName('labelName'); $mailbox->createLabel($userEmail, $label);

FirstOrCreateLabel: Create new label on the email with the labelName if it doesn't exist, (*85)

https://developers.google.com/gmail/api/reference/rest/v1/users.labels/create, (*86)

Example:, (*87)

``` php $mailbox = new LaravelGmailClass(config(), LaravelGmail::user());, (*88)

$label = new \Google_Service_Gmail_Label($this);
$label->setMessageListVisibility('show'); `show || hide`
$label->setLabelListVisibility('labelShow'); `labelShow || labelShowIfUnread || labelHide`
$label->setName('labelName');
$mailbox->firstOrCreateLabel($userEmail, $label);


## Attachment

use Dacastro4\LaravelGmail\Services\Message\Attachment ..., (*89)

$attachment = new Attachment;, (*90)


`$attachment->getId` Returns the ID of the attachment `$attachment->getFileName` Returns the file name of the attachment `$attachment->getMimeType` Returns the mime type Ex: application/pdf `$attachment->getSize` Returns the size of the attachment in bytes `$attachment->getData` Get the all the information from the attachment. If you call `getAttachmentsWithData` you won't need this method. `$attachment->saveAttachmentTo($path = null, $filename = null, $disk = 'local')` Saves the attachment on the storage folder. You can pass the path, name and disk to use. ## Messages `LaravelGmail::message()->all( $pageToken = null )` Returns all the emails from the inbox `LaravelGmail::message()->take(2)->all( $pageToken = null )` The `take` method limits the emails coming from the query by the number set `LaravelGmail::message()->get( $id )` Returns a single email with all the information ### Modifiers You can modify your query with these methods. For example: To get all unread emails: `LaravelGmail::message()->unread()->all()` `message()->unread()` `message()->from( $email )` `message()->in( $box = 'inbox' )` `message()->hasAttachment()` `message()->subject($subject)` `->after($date)` and `->before($date)` `message()->raw($query)` for customized queries All the possible filters are in the [Filterable Trait](https://github.com/dacastro4/laravel-gmail/blob/master/src/Traits/Filterable.php) Of course you can use as a fluent api. ``` php LaravelGmail::message() ->from('someone@gmail.com') ->unread() ->in('TRASH') ->hasAttachment() ->all()

Attachment

use Dacastro4\LaravelGmail\Services\Message\Attachment
...

$attachment = new Attachment;

$attachment->getId Returns the ID of the attachment, (*91)

$attachment->getFileName Returns the file name of the attachment, (*92)

$attachment->getMimeType Returns the mime type Ex: application/pdf, (*93)

$attachment->getSize Returns the size of the attachment in bytes, (*94)

$attachment->getData Get the all the information from the attachment. If you call getAttachmentsWithData you won't need this method., (*95)

$attachment->saveAttachmentTo($path = null, $filename = null, $disk = 'local') Saves the attachment on the storage folder. You can pass the path, name and disk to use., (*96)

Messages

LaravelGmail::message()->all( $pageToken = null ) Returns all the emails from the inbox, (*97)

LaravelGmail::message()->take(2)->all( $pageToken = null ) The take method limits the emails coming from the query by the number set, (*98)

LaravelGmail::message()->get( $id ) Returns a single email with all the information, (*99)

Modifiers

You can modify your query with these methods. For example:, (*100)

To get all unread emails: LaravelGmail::message()->unread()->all(), (*101)

message()->unread(), (*102)

message()->from( $email ), (*103)

message()->in( $box = 'inbox' ), (*104)

message()->hasAttachment(), (*105)

message()->subject($subject), (*106)

->after($date) and ->before($date), (*107)

message()->raw($query) for customized queries, (*108)

All the possible filters are in the Filterable Trait, (*109)

Of course you can use as a fluent api., (*110)

``` php, (*111)

LaravelGmail::message()
            ->from('someone@gmail.com')
            ->unread()
            ->in('TRASH')
            ->hasAttachment()
            ->all()

### Preload You can preload the body, header and the rest of every single email just by calling this method. `LaravelGmail::preload()` Example: ``` php LaravelGmail::message() ->from('someone@gmail.com') ->unread() ->in('TRASH') ->hasAttachment() ->preload() ->all()

Watch

https://developers.google.com/gmail/api/reference/rest/v1/users/watch, (*112)

Example:, (*113)

``` php $mailbox = new LaravelGmailClass(config(), $account->id);, (*114)

// One watch per account + need reinit every 24h+
$mailbox->stopWatch('example@gmail.com');

// Set watch for topic
$rq = new \Google_Service_Gmail_WatchRequest();
$rq->setTopicName('projects/YOUR_PROJECT_ID/topics/gmail');
$mailbox->setWatch('example@gmail.com', $rq);


### History https://developers.google.com/gmail/api/reference/rest/v1/users.history Example: ``` php $historyList = (new LaravelGmailClass(config(), $account->id)) ->historyList($data['emailAddress'], [ 'startHistoryId' => $startHistoryId, ]); foreach ($historyList->history as $chunk) { foreach ($chunk->messages as $msg) { ... } }

Frequent Issues

Login Required

If you're getting the Login Required error, try creating the gmail-json.json file under /storage/app/gmail/tokens/., (*115)

The Versions