Download the PHP package skn036/laravel-gmail-api without Composer

On this page you can find all versions of the php package skn036/laravel-gmail-api. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-gmail-api

Gmail Api For Laravel

This package is a wrapper around gmail api for Laravel from version 10 and upwards.

Installation

You can install this package via composer.

If you are using any google package from skn036 for the first time, please run the following command to publish the config file. It will create a config file google.php in your config directory.

If this config file is already published typically though any other google package from skn036, no need to run above command. Just add the gmail related scopes.

Adding gmail scope:

For the api to work properly, you should add at least https://www.googleapis.com/auth/gmail.modify scope from gmail. If you want to have full control over gmail like permanently deleting the resources, you should add the master permission https://mail.google.com/ to the scopes. Typically scopes are added by updating GOOGLE_SCOPES variable in your .env file. Multiple scopes should be given as space separated. For more details about gmail scopes, please read gmail documentation here.

Google Authentication

Google authentication is done on a separate package, which will be installed automatically with this package. Please check skn036/laravel-google-client for detailed instruction on the google authentication.

Why authentication on a separate package?

Google uses only one authentication per app created in google cloud console irrespective of how many services you use like gmail, calendar, drive, youtube etc. So keeping the authentication separate is always a good idea, if in case you want to add more services from google later on. skn036/laravel-google-client is easily extendable. While using other services, you can directly start implementing any google service on top of it without creating new app on google console and redoing the authentication again.

Getting Started

Skn036\Gmail\Gmail is the entry point to interact with gmail api. You can access it by using the facade or directly creating an instance of it.

Reading Messages From Gmail

To read the list of messages from gmail.

List response returns a instance of Skn036\Gmail\Message\GmailMessagesList which contains the list of messages, whether there's a next page, current page token, next page token and total messages. You can fetch the messages of the next page by calling next method or by passing the next page token to the list method. For fetching response of the previous page again, you should store the current page tokens and revert back to it if necessary.

$messageResponse->messages is a collection of Skn036\Gmail\Message\GmailMessage. Each message contains the necessary information about the message like id, thread id, from, to, cc, bcc, labels, subject, date, body, snippet, history id, references etc.

$messageResponse->hasNextPage is a boolean value which tells whether there's a next page or not.

$messageResponse->nextPageToken is a string value which contains the token to fetch the next page.

$messageResponse->currentPageToken is a string value which contains the token of the current page.

$messageResponse->total is a integer value which contains the total number of messages.

To fetch the messages of the next page, you can use next method or by passing the next page token to the list method.

Filtering Messages:

It is highly recommend to read gmail documentation on Refine searches on gmail and Searching for messages have a clear idea about the search queries.

To include messages from spam and trash folders, you can use the includeSpamTrash method. For set the per page limit, you can use the maxResults method.

To filter messages by email address, you can use the from, to, cc, bcc method. If you want to filter by any field use recipient method instead. These methods expects a email address or a array of email addresses as first argument. If multiple email addresses are given, by default it will do logically OR operation. If you want to do AND operation, you can pass "AND" as the second argument. Of course you can chain as much as filters needed.

To filter messages by subject or any specific word or phrase in the message, include or exclude words on the search use subject, search, includeWord and excludeWord respectively.

To filter by labels, you can use label method. It expects a label name or array of label names as first argument. If multiple labels are given, by default it will do logically OR operation. If you want to do AND operation, you can pass "AND" as the second argument.

Samely, you can filter by category also.

If you want to filter messages whether has specific connection or star, use has method.

For searching messages by it's status, use is method.

It is possible to search messages by it's location as well. Use in method for this.

To search by message size, use size, largerThan and smallerThan methods.

To find messages before or after any specific date, use before and after methods.

You can also use olderThan and newerThan methods to find messages older or newer than specific time.

Instead, if you want to pass the raw query string to the search use rawQuery method. This will override all other filters. For more details on how to write raw query, please read gmail documentation.

Getting a Single Message:

To get a single message, you can use the get method. It expects a message id as the first argument. It will return a instance of \Skn036\Gmail\Message\GmailMessage

Sending Emails

This packages usages symfony/mailer under the hood to send the emails. To send an email, first you should create a instance of Skn036\Gmail\Message\Sendable\Email.

you can add email "to" recipients by either to or addTo method. The difference between these two methods is, multiple chaining of to method will replace the previous recipients, while addTo will append the recipients.

if you want to pass the name of the recipient along with the email address, you need to give each function argument as array of email and name. Instead, you can pass a instance of Skn036\Gmail\Message\GmailMessageRecipient also.

Samely, you can add email "cc" and "bcc" recipients by using cc, bcc, addCc and addBcc methods.

To set the name of the sender, you can use setMyName method. Receivers of the email will see this name as the sender of the email. If not set then it will take the name from synced google account's name.

To retrieve the set recipients, you can use getTo, getCc and getBcc methods.

To set the subject of message use subject method.

You can set the priority of the message by priority method. It expects a integer value from 1 to 5, while 1 is the highest priority and 5 is the lowest. By default priority is set to 3 which is normal priority.

To set the body of the message, you can use body method. It supports both html and text string.

Instead if you want to set the body from the view file you can use view method. It expects the view file name and data to be passed to the view.

You can also use markdown files to set the body of the message. Use markdown method for this.

To add attachments to the email, you can use attach method. Multiple files can be attached by passing as individual arguments. Each argument expects path to file (w.r to the storage folder) or a instance of \Illuminate\Http\UploadedFile. Multiple chaining of the attach method will replace the previous attachments. to add attachments to the previous attachments, you can use addAttachment method instead.

To embed inline images on email body, you can use embed method. Multiple images can be embedded by passing as individual arguments. Each argument expects an array. First item of the array should be path to file (w.r to the storage folder) or a instance of \Illuminate\Http\UploadedFile and second item of the array should be the name of cid image. Image to embed properly, you must reference the cid name in the html body of the email like <img src="cid:{name}"> or <div background="cid:{name}"> ... </div>.

Same as attachments, multiple chaining of the embed method will replace the previous embedded images. To add embedded images to the previous images, you can use addEmbed method instead.

you can get the set properties by getter method generally like getSubject, getPriority, getBody, getAttachments, getEmbeds etc.

Sending The Email:

When all of the properties are set, you can send the email by calling send method. It will return a instance of \Skn036\Gmail\Message\GmailMessage.

The Message Instance \Skn036\Gmail\Message\GmailMessage

This instance contains all the information about the message as well as necessary helper methods to interact with the message.

Message public properties are as follows:

$message->id Id of the message.

$message->threadId Thread id of the message.

$message->headerMessageId Message-id header on the message.

$message->replyTo In-reply-to header of the message which is the header message id if the message is replied on some message.

$message->from From recipient.

$message->to Collection of to recipients.

$message->cc Collection of cc recipients. By default, bcc is not public property. If you want to access it anyway, you can use $message->getBcc().

$message->labels Collection of label ids.

$message->subject Subject of the message.

$message->date Datetime of the message as a Carbon instance.

$message->body Body of the message. By default it will return html body. If not available it will return text body. if you want to access both body individually you can call $message->getHtmlBody() or $message->getTextBody().

$message->snippet Snippet of the message.

$message->historyId History id of the message.

$message->references References message header.

$message->attachments Collection of attachments.

Working With Attachments:

$message->attachments is a Collection of Skn036\Gmail\Message\GmailMessageAttachment. Each attachment contains the following properties.

$attachment->id Id of the attachment.

$attachment->filename Filename of the attachment.

$attachment->mimeType Mime type of the attachment.

$attachment->size Size of the attachment.

$attachment->data Base64 encoded raw file content. By default it will be null. The content will be downloaded when called save, download or getData method.

For saving attachment to the file system, you can use save method. Path can be passed as function argument. This functionality usages Laravel's Storage facade. So path should be given w.r to public disk. If the path is not given, it will save the file to the path configured by config('google.gmail.attachment_path').

To save all the attachments at once, you may use saveAllAttachments method.

Rather than saving the attachment, if you want to download the attachment directly to your browser, you can use download method.

If you want to get the raw data of the attachment without saving or downloading, you can use getData method.

Replying Or Forwarding Message:

Gmail has some criteria that should met in order to messages being on the same thread. To create a reply or forward message, you can use createReply and createForward methods. Both methods will create a instance of Skn036\Gmail\Message\Sendable\Email setting up necessary headers and subject to meet criteria from gmail. Then rest of the steps are same as sending email mentioned above.

Creating Draft On The Message:

Creating draft on the message is similar to creating reply or forward. You can use createDraft method to create a draft on the message. It will create a instance of Skn036\Gmail\Draft\Sendable\Draft setting up necessary headers and subject to meet criteria from gmail. Then rest of the steps are same as sending email mentioned above.

NOTE: Creating reply or forward will only set the necessary headers and subject to meet the criteria from gmail for being in same thread. It will not set the recipients, body or attachments. You should set them manually. This is because, most likely, these values will be updated on the frontend by user input before sending the email and implementation of these generally vary from project to project.

Changing The Message Labels:

To add or remove labels from the message, you can use addLabel and removeLabel methods. It expects a label id or array of label ids as the first argument.

If you want to add and remove on a single operation you can use modifyLabels method. It expects two arguments. First argument should be array of labels to add and second argument should be array of labels to remove.

Deleting Messages:

To move and remove messages from trash, you can use trash and untrash methods.

To delete the message permanently, you can use delete method. NOTE: Once the message is deleted, it can't be recovered. https://mail.google.com/ scope is required to delete the message permanently.

You may call these methods directly on the message resource rather than on the message instance. All you need to do is to pass the message id as the first argument and rest of the arguments as mentioned above.

Accessing Raw Gmail Message:

If you want to access the raw message from gmail, you can use getRawMessage method. It will return the original message received from gmail which is a instance of \Google_Service_Gmail_Message.

To get any header of the message you can use getHeader method. It expects the header name as the first argument.

Working With Batches:

If you want to add or remove labels of multiple messages at once you use batchAddLabels and batchRemoveLabels methods. These methods expects a array or Collection of message ids or Skn036\Gmail\Message\GmailMessage as the first argument and label id or array of label ids on the second argument.

To delete multiple messages at once, you can use batchDelete method. NOTE: Once the message is deleted, it can't be recovered. https://mail.google.com/ scope is required to delete the message permanently.

Gmail Drafts

Drafts are the message instances in gmail which are not sent yet. Typically they have a DRAFT label. To read the list of drafts from gmail.

List response returns a instance of Skn036\Gmail\Draft\GmailDraftsList which contains the list of drafts and other properties same as messages list. You can fetch the drafts of the next page by calling next method or by passing the next page token to the list method. For fetching response of the previous page again, you should store the current page tokens and revert back to it if necessary.

$draftResponse->drafts is a collection of Skn036\Gmail\Draft\GmailDraft. Each draft contains id and underlying message instance.

$draftResponse->hasNextPage is a boolean value which tells whether there's a next page or not.

$draftResponse->nextPageToken is a string value which contains the token to fetch the next page.

$draftResponse->currentPageToken is a string value which contains the token of the current page.

To fetch the drafts of the next page, you can use next method or by passing the next page token to the list method.

Filtering Drafts:

Api for filtering drafts is same as messages. You can use all the filters mentioned on the messages section to filter drafts.

Getting a Single Draft:

To get a single draft, you can use the get method. It expects a draft id as the first argument. It will return a instance of \Skn036\Gmail\Draft\GmailDraft

If you wish to access the underlying raw draft from gmail, you can use getRawDraft method. It will return the original draft received from gmail which is a instance of \Google_Service_Gmail_Draft.

Creating, Updating And Sending Drafts:

To create a draft you can call create method. It will return a instance of \Skn036\Gmail\Draft\Sendable\Draft.

To edit a already saved draft, you can call edit method on draft instance. It will return a instance of \Skn036\Gmail\Draft\Sendable\Draft.

Now you can edit the properties of the draft like you do on the email. Once you are done, you can call save method. It will save the draft on the gmail and return a instance of \Skn036\Gmail\Draft\GmailDraft. Or If you want to send the draft after editing, you can call send method. It will send the draft as email and return a instance of \Skn036\Gmail\Message\GmailMessage.

NOTE: When you are editing the draft, you need to pass all the properties every time you edit, because gmail will replace the previous properties with the new one. So if you want to keep the previous properties, you should get the message from the draft instance and pass them again.

If you wish to send a already saved draft without further need of editing, you can use send method directly on the draft instance. It will send the last saved draft as email.

Deleting Drafts:

You may delete a draft by calling delete method on the draft instance or passing the id to the draft. NOTE: Full mailbox permission is required for this action.

Updating Labels On Drafts:

Underlying message of GmailDraft is a instance of GmailMessage. So you can use the same methods mentioned on the message section to add, remove or modify labels.

Managing Gmail Threads

Threads are the collection of messages grouped together which are on same conversation.

Reading Threads From Gmail:

To read the list of threads from gmail.

List response returns a instance of Skn036\Gmail\Thread\GmailThreadsList which contains the list of threads, whether there's a next page, current page token, next page token and total threads. You can fetch the threads of the next page by calling next method or by passing the next page token to the list method. For fetching response of the previous page again, you should store the current page tokens and revert back to it if necessary.

$threadResponse->threads is a collection of Skn036\Gmail\Thread\GmailThread. Each thread contains the necessary information like id, Collection of messages, snippet, history id etc.

$threadResponse->hasNextPage is a boolean value which tells whether there's a next page or not.

$threadResponse->nextPageToken is a string value which contains the token to fetch the next page.

$threadResponse->currentPageToken is a string value which contains the token of the current page.

$threadResponse->total is a integer value which contains the total number of threads.

To fetch the threads of the next page, you can use next method or by passing the next page token to the list method.

Filtering Threads:

Api for filtering threads is same as messages. You can use all the filters mentioned on the messages section to filter threads.

Getting a Single Thread:

To get a single thread, you can use the get method. It expects a thread id as the first argument. It will return a instance of \Skn036\Gmail\Thread\GmailThread

If you wish to access the underlying raw thread from gmail, you can use getRawThread method. It will return the original draft received from gmail which is a instance of \Google_Service_Gmail_Thread.

Changing The Thread Labels:

To add or remove labels from the thread, you can use addLabel and removeLabel methods. It expects a label id or array of label ids as the first argument. Gmail will automatically modify labels of all the messages in the thread.

If you want to add and remove on a single operation you can use modifyLabels method. It expects two arguments. First argument should be array of labels to add and second argument should be array of labels to remove.

Deleting Threads:

To move and remove threads from trash, you can use trash and untrash methods.

To delete the thread along with it's messages permanently, you can use delete method. NOTE: Once the thread is deleted, it can't be recovered. https://mail.google.com/ scope is required to delete the thread permanently.

As usual, you may call these methods directly on the thread resource rather than on the Skn036\Gmail\Thread\GmailThread instance. All you need to do is to pass the thread id as the first argument and rest of the arguments as mentioned above.

Working With Gmail Labels

To read the list of labels from gmail.

List response returns a instance of Skn036\Gmail\Label\GmailLabelsList which contains the list of threads.

$labelResponse->labels is a collection of Skn036\Gmail\Label\GmailLabel. Each label contains the necessary information like id, name, type, labelListVisibility, messageListVisibility, textColor, backgroundColor, messagesTotal, messagesUnread, threadsTotal, threadsUnread etc.

Getting a Single Label:

To get a single label, you can use the get method. It expects a label id as the first argument. It will return a instance of \Skn036\Gmail\Label\GmailLabel

If you wish to access the underlying raw label from gmail, you can use getRawLabel method. It will return the original draft received from gmail which is a instance of \Google_Service_Gmail_Label.

Creating Label:

To create a new label on gmail, you can use create method. It expects a array as first argument. The array can contain the following keys: name, labelListVisibility, messageListVisibility, textColor, backgroundColor. Only name is mandatory. Rest of the keys are optional. for more info about this parameters and their valid values, please read gmail documentation on labels.

Updating Label:

To update a label, you can use update method. It expects a label id as the first argument and array as the second argument. The array can contain the following keys: name, labelListVisibility, messageListVisibility, textColor, backgroundColor. All of the keys are optional.

Deleting Label:

To delete a label you can use delete method. It expects a label id as the first argument.

Watching Changes On Gmail Mailbox

If you wish to watch for changes on the synced mailboxes like messages added/deleted or labels added/deleted to the resources, you should start watching the mailbox by calling start method on watch resource.

Gmail provides gmail push notification via google pubsub. You should give gmail specific permissions to the pubsub topic and add a subscription. You should select response type to push on subscription and give the endpoint of you app where you expect the notifications. For more details on how to setup the pub sub, please read gmail documentation on push notifications. After all the setup is done, you should add the topic name to GOOGLE_PUB_SUB_TOPIC on the .env file.

If you want to watch for changes on the specific labels, you can pass the label ids as an array the first argument to the start method and on the second argument you can pass 'include' or 'exclude' depending to your expectation. For more info, please check gmail documentation on watch.

To get continuous push notification from gmail, you should call the watch start everyday for all synced gmail accounts via a cronjob.

if your watch is working correctly, you should receive a notification on the endpoint (post request) you have given on the pub sub subscription. On the request body you will receive a json and base64 encoded data. If you extract, it will give historyId and emailAddress of the synced account.

You should keep a track of the last used historyId and fetch all histories from the last historyId by using histories resource mentioned below. If you are syncing gmail mailbox to your local database, you can use these histories to keep your database updated.

Gmail Histories

To read histories from gmail you can use list method on histories resource. You must give the start history id to fetch the histories from that point. If you don't pass this parameter, it will throw an exception. You can set this parameter by calling startHistoryId method.

if you wish to fetch the histories of specific label or action, you can call labelId and historyTypes method respectively. You may also set the maximum number of histories to fetch by calling maxResults method.

List response returns a instance of Skn036\Gmail\History\GmailHistoriesList which contains the list of histories, whether there's a next page, current page token, next page token. You can fetch the histories of the next page by calling next method or by passing the next page token to the list method.

$historyResponse->histories is a collection of Skn036\Gmail\History\GmailHistory.

$historyResponse->hasNextPage is a boolean value which tells whether there's a next page or not.

$historyResponse->nextPageToken is a string value which contains the token to fetch the next page.

$historyResponse->currentPageToken is a string value which contains the token of the current page.

To fetch the histories of the next page, you can use next method or by passing the next page token to the list method.

if you want to fetch all the histories and merge them into a collection, you can use while loop of PHP.

Each history is a instance of Skn036\Gmail\History\GmailHistory. It contains the necessary information like id, action, messagesAdded, messagesDeleted, labelsAdded, labelsRemoved etc.

$history->id id of the history

$history->messagesAdded is a array of \Google_Service_Gmail_HistoryMessageAdded. It will contain data if message added on the history.

$history->messagesDeleted is a array of \Google_Service_Gmail_HistoryMessageDeleted. It will contain data if message deleted on the history.

$history->labelsAdded is a array of \Google_Service_Gmail_HistoryLabelAdded. It will contain data if label added on the history.

$history->labelsRemoved is a array of \Google_Service_Gmail_HistoryLabelRemoved. It will contain data if label removed on the history.

$history->messages is a collection of \Google_Service_Gmail_Message.

$history->action is a string contains the action. enum values are either of 'message-added' 'message-deleted' 'labels-added' 'labels-removed'. If there's no action of the history it should return null. Checking this property is a good way to identify that if the history has any action or not.

Changelog

Please see CHANGELOG for more information on what has changed recently.

License

The MIT License (MIT). Please see License File for more information.


All versions of laravel-gmail-api with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2||^8.3
illuminate/contracts Version ^10||^11
skn036/laravel-google-client Version ^1
symfony/mailer Version ^6||^7
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package skn036/laravel-gmail-api contains the following files

Loading the files please wait ....