PHP code example of skn036 / laravel-gmail-api

1. Go to this page and download the library: Download skn036/laravel-gmail-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

skn036 / laravel-gmail-api example snippets


use Skn036\Google\GoogleClient;

class Youtube extends GoogleClient
{
    // GoogleClient will handle user authentication, keeping, refreshing and retrieving auth tokens.

    public function __construct(
        string|int|null $userId = null,
        ?string $usingAccount = null,
        ?array $config = null
    ) {
        parent::__construct($userId, $usingAccount, $config);
    }

    // implement youtube related functionality.
}

// using facade
use Skn036\Gmail\Facades\Gmail;
$message = Gmail::messages()->get($messageId);

// if you want to pass constructor parameters like user id, email account (if using multiple accounts per user)
// or overriding config, use the base class instead.
use Skn036\Gmail\Gmail;
$gmail = new Gmail(auth()->id(), '[email protected]', $customConfig);

use Skn036\Gmail\Facades\Gmail;

$messageResponse = Gmail::messages()->maxResults(20)->list();

$nexPageResponse = $messageResponse->next();
// or
$nextPageResponse = $gmail->messages()->list($messageResponse->nextPageToken);

$messageResponse = Gmail::messages()->

$messages = Gmail::messages()
    ->from(['[email protected]', '[email protected]'])
    ->to('[email protected]')
    ->cc(['[email protected]', '[email protected]'], 'AND')
    ->bcc(['[email protected]', '[email protected]'], 'OR')
    ->recipient('[email protected]')
    ->list();

$messages = Gmail::messages()
    ->subject('Nice to meet you!!!')
    ->search('hello world')
    ->

Gmail::messages()->label('inbox');
// or
Gmail::messages()->label(['inbox', 'important'], 'AND');
// or
Gmail::messages()->label(['draft', 'spam', 'trash', 'sent', 'starred']);

Gmail::messages()->category('primary');
// or
Gmail::messages()->category(['promotions', 'social'], 'AND');
// or
Gmail::messages()->category(['updates', 'reservations', 'purchases']);

Gmail::messages()->has('attachment');
// or
Gmail::messages()->has(['youtube', 'drive'], 'AND');
// or
Gmail::messages()->has(['yellow-star', 'orange-star', 'red-star']);

Gmail::messages()->is('unread');
// or
Gmail::messages()->is(['read', 'important'], 'AND');
// or
Gmail::messages()->is(['starred', 'muted']);

Gmail::messages()->in('anywhere');
// or
Gmail::messages()->in(['snoozed', 'spam'], 'AND');
// or
Gmail::messages()->in(['inbox', 'sent', 'draft']);

// by size
Gmail::messages()->size('1000000');
// size larger than
Gmail::messages()->largerThan('10M');
// size smaller than
Gmail::messages()->smallerThan('100K');

Gmail::messages()->before('2021-01-01 23:10:30');
Gmail::messages()->after(Carbon::now()->subDays(10));

Gmail::messages()->olderThan('1d');
Gmail::messages()->newerThan('1y');

$messages = Gmail::messages()
    ->rawQuery('in:sent after:1388552400 before:1391230800 subject: Hello!!!')
    ->

$message = Gmail::messages()->get($messageId);

$email = Gmail::messages()->create(); // will create a instance of Skn036\Gmail\Message\Sendable\Email

$email->to('[email protected]', '[email protected]');
$email->addTo('[email protected]', '[email protected]'); // these emails will append to previous

$to = [
    ['[email protected]', 'Test User'],
    '[email protected]',
    new \Skn036\Gmail\Message\GmailMessageRecipient('[email protected]', 'John Doe'),
];

$email->to(...$to);

$email->cc(['[email protected]', 'Test User'], '[email protected]');
$email->addCc(new \Skn036\Gmail\Message\GmailMessageRecipient('[email protected]', 'John Doe'));

$email->bcc(['[email protected]', 'Test User'], ['[email protected]', 'Foo Bar']);
$email->addBcc('[email protected]');

$email->setMyName('John Doe');

$email->subject('Hello World!!!');

$email->priority(1);

$email->body('<div>Cool body</div>');

$email->view('emails.welcome', ['name' => 'John Doe']);

$email->markdown('emails.welcome', ['name' => 'John Doe']);

$files = $request->file('attachments');
$email->attach(...$files);

// or if the files exists in your storage folder, you can pass the file path
$email->attach('app/public/attachments/file1.pdf', 'app/public/attachments/file2.pdf');

$files = $request->file('attachments');
$cidNames = $request->cid_names;

$embedFiles = array_map(
    function ($file, $cidName) {
        return [$file, $cidName];
    },
    $files,
    $cidNames
);
$email->embed(...$embedFiles);

// or if the files exists in your storage folder, you can pass the file path
$email->embed(
    ['app/public/attachments/watermark.png', 'watermark'],
    ['app/public/attachments/logo.png', 'logo']
);

// in the email body, you can reference the cid name like <img src="cid:logo"> or <body background="cid:watermark"> ... </body>

$message = $email->send();

$message = Gmail::messages()->get($messageId);
// or
$message = Gmail::messages()->list()->messages->first();

$attachment = $message->attachments->first();
$savedPath = $attachment->save('gmail-attachments');

// or you can directly save from the message instance
$savedPath = $message->saveAttachment($attachment->id, 'gmail-attachments');

$savedPaths = $message->saveAllAttachments();

public function downloadAttachment(Request $request) {
    $message = Gmail::messages()->get($request->message_id);

    $attachment = $message->attachments->first();
    return $attachment->download();

    // or
    return $message->downloadAttachment($request->attachment_id);
}

$attachment = $attachment->getData();
$rawFile = $attachment->decodeBase64($attachment->data);

// creating a forward email
$email = $message->createForward();

// creating a reply email
$email = $message->createReply();

$replyBody =
    "Hi! This is a reply to your message. \n\n" .
    'On ' .
    $message->date->format('l, F j, Y \a\t g:i A') .
    ', ' .
    "$message->from->name < $message->from->email >" .
    " wrote: \n" .
    $message->body;

$repliedMessage = $email
    ->to($message->from)
    ->body($replyBody)
    ->send();

// creating a reply/forward draft instance
$sendableDraft = $message->createDraft();

$draftBody =
    "Hi! This is a draft on the message. It is not necessarily to send immediately. \n\n" .
    'On ' .
    $message->date->format('l, F j, Y \a\t g:i A') .
    ', ' .
    "$message->from->name < $message->from->email >" .
    " wrote: \n" .
    $message->body;

$draft = $sendableDraft
    ->to($message->from)
    ->cc(...$message->cc->values()->all())
    ->body($draftBody)
    ->attach(...$attachments);

$draft = $draft->save(); // this will create a draft on the gmail

// add labels
$message = $message->addLabels(['INBOX', 'IMPORTANT', 'UNREAD']);

// remove labels
$message = $message->removeLabels('SPAM');

$message->modifyLabels(['INBOX', 'IMPORTANT', 'UNREAD'], ['SPAM']);

$message->trash(); // moved to trash

$message->untrash(); // removed from trash

$message->delete();

$email = Gmail::messages()->createReply($messageId);

$message = Gmail::messages()->addLabel($messageId, 'IMPORTANT');

$message = Gmail::messages()->trash($messageId);

$rawMessage = $message->getRawMessage();

$rawTo = $message->getHeader('to');

$messageResource = Gmail::messages();
$messages = $messageResource->list()->messages;

// add labels
$messageResource->batchAddLabels($messages, ['IMPORTANT', 'UNREAD']);

// remove labels
$messageIds = $messages->pluck('id');
$messageResource->batchRemoveLabels($messageIds, 'SPAM');

// adding and removing labels on a single operation
$messageResource->batchModifyLabels($messages, ['IMPORTANT', 'UNREAD'], 'SPAM');

$messageResource->batchDelete($messages);

use Skn036\Gmail\Facades\Gmail;

$draftResponse = Gmail::drafts()->maxResults(20)->list();

$nexPageResponse = $draftResponse->next();
// or
$nextPageResponse = $gmail->drafts()->list($draftResponse->nextPageToken);

$drafts = Gmail::drafts()
    ->(['[email protected]', '[email protected]'])
    ->in(['DRAFT', 'SPAM'])
    ->list()->drafts;

$draft = Gmail::drafts()->get($draftId);

$rawDraft = $draft->getRawDraft();

$sendableDraft = Gmail::drafts()->create();

// editing from the \Skn036\Gmail\Draft\GmailDraft instance
$draft = Gmail::drafts()->get($draftId);
$sendableDraft = $draft->edit();

// or edit the instance by passing the draft id
$sendableDraft = Gmail::drafts()->edit($draftOrDraftId);

$draft = $sendableDraft
    ->to('[email protected]', ['[email protected]', 'John Doe'])
    ->cc('[email protected]')
    ->subject('First draft')
    ->body('Hello World!!!')
    ->attach(...$request->file('attachments'));

$savedDraft = $draft->save(); // saves the created or edited draft
// or
$sentMessage = $draft->send(); // sends the draft as email

$draft = Gmail::drafts()->get($draftId);
$message = $draft->send();

$draft = Gmail::drafts()->get($draftId);
$draft->delete();

// or
Gmail::drafts()->delete($draftId);

$draft = Gmail::drafts()->get($draftId);
$message = $draft->message;

$message->addLabel('IMPORTANT');

use Skn036\Gmail\Facades\Gmail;

$threadResponse = Gmail::threads()->maxResults(20)->list();

$nexPageResponse = $threadResponse->next();
// or
$nextPageResponse = $gmail->threads()->list($threadResponse->nextPageToken);

$threads = Gmail::threads()
    ->Carbon::now()->subDays(10))
    ->is(['unread'])
    ->list()->threads;

$thread = Gmail::threads()->get($threadId);

$rawThread = $thread->getRawThread();

// add labels
$thread->addLabels(['INBOX', 'IMPORTANT', 'UNREAD']);

// remove labels
$thread->removeLabels('SPAM');

$thread->modifyLabels(['INBOX', 'IMPORTANT', 'UNREAD'], ['SPAM']);

$thread->trash(); // moved to trash

$thread->untrash(); // removed from trash

$thread->delete();

$thread = Gmail::threads()->addLabel($threadId, 'IMPORTANT');

$thread = Gmail::threads()->trash($threadId);

use Skn036\Gmail\Facades\Gmail;

$labelResponse = Gmail::labels()->list();

$label = Gmail::labels()->get($labelId);

$rawLabel = $draft->getRawLabel();

$label = Gmail::labels()->create([
    'name' => 'Test Label',
    'messageListVisibility' => 'show',
    'labelListVisibility' => 'labelShow',
    'textColor' => '#434343',
    'backgroundColor' => '#43d692',
]);

$label = Gmail::labels()->update('Label_20', [
    'textColor' => '#000000',
    'backgroundColor' => '#cca6ac',
]);

Gmail::labels()->delete('Label_20');

$watchResponse = Gmail::watch()->start(); // starting the watch on the mailbox

Gmail::watch()->stop(); // stopping the watch on the mailbox

$watchResponse = Gmail::watch()->start(['INBOX', 'IMPORTANT'], '

$response = json_decode($request->getContent(), true);
$data = json_decode(base64_decode($response['message']['data']), true);

$historyResponse = Gmail::histories()->startHistoryId('123456')->list();

$historyResponse = Gmail::histories()
    ->startHistoryId('123456')
    ->labelId('INBOX')
    ->historyTypes(['messageAdded', 'labelRemoved'])
    ->maxResults(200)
    ->list();

$nexPageResponse = $historyResponse->next();
// or
$nextPageResponse = $gmail->histories()->list($historyResponse->nextPageToken);

$historyResponse = Gmail::histories()->startHistoryId('123456')->list();
$histories = $historyResponse->histories;

while ($historyResponse->hasNextPage) {
    $historyResponse = $historyResponse->next();
    $histories = $histories->merge($historyResponse->histories);
}
bash
php artisan vendor:publish --provider="Skn036\Google\GoogleClientServiceProvider"