GithubHelp home page GithubHelp logo

dacastro4 / laravel-gmail Goto Github PK

View Code? Open in Web Editor NEW
284.0 16.0 128.0 318 KB

Laravel wrapper for the Gmail API

License: MIT License

PHP 100.00%
laravel-gmail gmail-api laravel laravel-5-package gmail

laravel-gmail's Introduction

Laravel Gmail

Build Status Scrutinizer Code Quality GitHub issues Total Downloads Monthly Downloads GitHub license

Gmail

Gmail API for Laravel 9

You need to create an application in the Google Console. Guidance here.

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.

Requirements

  • PHP ^8.0
  • Laravel 9

Installation

Add dacastro4/laravel-gmail to composer.json.

"dacastro4/laravel-gmail": "^6.1"

Run composer update to pull down the latest version.

Or run

composer require dacastro4/laravel-gmail

Now open up config/app.php and add the service provider to your providers array.

'providers' => [
    Dacastro4\LaravelGmail\LaravelGmailServiceProvider::class,
]

Now add the alias.

'aliases' => [
    'LaravelGmail' => Dacastro4\LaravelGmail\Facade\LaravelGmail::class,
]

For laravel >=5.5 that's all. This package supports Laravel new Package Discovery.

For <= PHP 7.4 compatibility use version v5.0

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

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

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

Migration from 2.0 to 3.0

Requires Laravel 6 and you only have to change the dependency to "laravel/laravel": "^6.0"

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"

I had to change version because of a typo and that might break apps calling those attributes.

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

Mail Class $threatId => $threadId

Replyable Class $mail->setReplyThreat() => $mail->setReplyThread()

and so on.

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"

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.

Configuration

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

GOOGLE_PROJECT_ID=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URI=
GOOGLE_ALLOW_MULTIPLE_CREDENTIALS
GOOGLE_ALLOW_JSON_ENCRYPT

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

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'
    ],

Example

Welcome 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:

$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.

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.

Documentation

Basic

LaravelGmail::getAuthUrl Gets the URL to auth the user.

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

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

LaravelGmail::logout Logs out the user

LaravelGmail::check Checks if the user is logged in

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

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.

$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

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

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

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

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

$mail->subject( $subject ) sets the subject of the email

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

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

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

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

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

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

$mail->send() sends a new email

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

Mail

$mail->getId returns the email's ID

$mail->getInternalDate returns date in UNIX format

$mail->getDate returns a Carbon date from the header of the email

$mail->getLabels returns an array of all the labels of the email

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

$mail->getSubject returns an string of the subject

$mail->getFrom Returns an array with name and email of sender

$mail->getFromName Returns string of name

$mail->getFromEmail Returns string of email

$mail->getTo Returns an array with name and email of all recipients

$mail->getDeliveredTo Returns the email of the receiver

$mail->getPlainTextBody Returns the plain text version of the email

$mail->getRawPlainTextBody Returns the raw version of the body base64 encrypted

$mail->hasAttachments Returns a boolean if the email has attachments

$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()

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

Labels

$mail->markAsRead Removes the 'UNREAD' label from the email.

$mail->markAsUnread Adds the 'UNREAD' label to the email.

$mail->markAsImportant Adds the 'IMPORTANT' label to the email.

$mail->markAsNotImportant Removes the 'IMPORTANT' label from the email.

$mail->addStar Adds the 'STARRED' label to the email.

$mail->removeStar Removes the 'STARRED' label from the email.

$mail->sendToTrash Adds the 'TRASH' label to the email.

$mail->removeFromTrash Removes the 'TRASH' label from the email.

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

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

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

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

Listing: List all the labels of the email

https://developers.google.com/gmail/api/reference/rest/v1/users.labels/list

Example:

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

Create: Create new label on the email with the labelName

https://developers.google.com/gmail/api/reference/rest/v1/users.labels/create

Example:

    $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

https://developers.google.com/gmail/api/reference/rest/v1/users.labels/create

Example:

    $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->firstOrCreateLabel($userEmail, $label);

Attachment

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

$attachment = new Attachment;

$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

Of course you can use as a fluent api.

    LaravelGmail::message()
                ->from('[email protected]')
                ->unread()
                ->in('TRASH')
                ->hasAttachment()
                ->all()

Attachment

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

$attachment = new Attachment;

$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

Of course you can use as a fluent api.

    LaravelGmail::message()
                ->from('[email protected]')
                ->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:

    LaravelGmail::message()
                ->from('[email protected]')
                ->unread()
                ->in('TRASH')
                ->hasAttachment()
                ->preload()
                ->all()

Watch

https://developers.google.com/gmail/api/reference/rest/v1/users/watch

Example:

    $mailbox = new LaravelGmailClass(config(), $account->id);

    // One watch per account + need reinit every 24h+
    $mailbox->stopWatch('[email protected]');

    // Set watch for topic
    $rq = new \Google_Service_Gmail_WatchRequest();
    $rq->setTopicName('projects/YOUR_PROJECT_ID/topics/gmail');
    $mailbox->setWatch('[email protected]', $rq);

History

https://developers.google.com/gmail/api/reference/rest/v1/users.history

Example:

    $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/.

laravel-gmail's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-gmail's Issues

feature request: ->take(5) or ->some(5) instead of all()

Love how you structured all of this. This has definitely saved me a ton of setup time to work with gmail api.

But as you said, it's a work in progress.

For my use case, the current filters aren't adequate enough to limit my query.

Currently this returns 100 messages and it takes a long time if I want to loop through them.

$messages = LaravelGmail::message()->from('[email protected]')->all();

if I do this, it takes like 1 second:

$messages = LaravelGmail::message()->from('[email protected]')->all();
dump($messages);

this times out...

$messages = LaravelGmail::message()->from('[email protected]')->preload()->all();
dump($messages);

doing this takes 17 seconds.....


		$messages = LaravelGmail::message()->from('[email protected]')->all();

		$count = 0;
		foreach ($messages as $message) 
		{
			// $body = $message->getHtmlBody();
			$subject = $message->load()->getSubject();

			dump($subject);
			// dump($body);

			if ($count > 5)
				break;
			else
				$count++;
		}
	

What if we could do this?

$messages = LaravelGmail::message()->from('[email protected]')->preload()->take(5);

The goal being to increase performance?

Or am I missing something really obvious? Like some date filters...

Error namefrom

Excellent input, I found an error to solve, the error is when assigning the value to the nameFrom variable you placed nameTo, in the Replyable.php file

public function from( $from, $name = null )
{
$this->from = $from;
$this->nameTo = $name; <---this line
return $this;
}

i haves a error in email sending in laravel

$mail = new Mail();
$mail->to($data['to'])->from('us****@piecyfer.com')->subject('text')->message('this is trhe testing email')->send();

when i use to this code i wall received this kindly guide me about how to send email ;
Call to undefined method Illuminate\Support\Facades\Mail::to() (View: C:\xampp\htdocs\mygoogleapi\resources\views\welcome.blade.php)

Class 'Dacastro4\LaravelGmail\Facades\LaravelGmail' not found

I kept getting this error.

Class 'Dacastro4\LaravelGmail\Facades\LaravelGmail' not found

I have tried everything clearing cache, reinstalling both v0.4.1 and v0.4

I am running Laravel v5.4 and followed the installation. I added both provider and the fascade.

Please help, thanks!

No credentials found.

Dacastro4\LaravelGmail\Exceptions\AuthException
No credentials found.

I've renamed the env variable of 'credentials_file_name' => env( 'GOOGLE_CREDENTIALS_NAME', 'client.json') with the downloaded file from Google stored in the root of my directory.

Any advice on this? Thanks a bunch for your work on this!

Fatal Error

I am getting the following error once I log into my Gmail account and redirect back to the app URL

Dacastro4\LaravelGmail\Services\Message and Dacastro4\LaravelGmail\Traits\SendsParameters define the same property ($params) in the composition of Dacastro4\LaravelGmail\Services\Message. However, the definition differs and is considered incompatible. Class was composed

Any ideas?

Unable to get Mime Type

When using $attachment->getMimeType() :

Dacastro4\LaravelGmail\Services\Message\Attachment::$getMimeType

Return subject without preload?

Hi, there is such a issue.

How to return getSubject() without using preload(), load() ? (loading takes a very looong time with them)

For ex:

Return: $message = LaravelGmail::message()->take(100)->in('inbox')->all();

How to use {{ $message->getSubject() }} Or how to return getheaders() in the main query?

error when the email has no html ?

Pretty simple error, trying to fix it myself but I'm sure you could do it much quicker.

If the email is ONLY plain text with no html, we get an error. If the email has html in it, then all works fine.

<?php

namespace App\Http\Controllers;


use LaravelGmail;
use Illuminate\Http\Request;

class TestGmailApiController extends Controller
{


	/**
	 * testing
	 *
	 * @return void
	 */
	public function test ()
	{
		//$messages = LaravelGmail::message()->from('[email protected]')->take(5)->all();
		
		$messages = LaravelGmail::message()->from('[email protected]')->take(5)->all();

		foreach ($messages as $message) 
		{

			dump($message->load()->getHtmlBody());
			dump($message->load()->getRawPlainTextBody());
			dump($message->load()->getPlainTextBody());


		}
	}


The error message is

Whoops, looks like something went wrong.
1/1
ErrorException in UserRefreshCredentials.php line 91:
Your application has authenticated using end user credentials from Gooogle Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Cloud SDK, you might receive a "quota exceeded" or "API not enabled" error. For more information about service accounts, see https://cloud.google.com/docs/authentication/.

Great, now gmail keeps asking for a service account... might as well be asking me to create a rocket and successfully launch it into space. Thanks Google.

Anyway,
I can't give you the error message, but I spent time on it so I know the problem.

the problem is $body is null on line 376 in Services/Message/Mail.php

	public function getBody( $type = 'text/plain' )
	{
		$part = $this->getBodyPart( $type );
		$body = $part->getBody();

		return $body->getData();
	}

basically in this case something goes null that maybe you're not handling when getBodyPart() or Get Part() is called

when the email is plaintext only..
have you ever tried this on a plaintext email?

Page token missing

Page token is missing when using limit data.

LaravelGmail::message()->limit(10)->in( $box = 'inbox' )->preload()->all();

How can i access pagetoken.

error "Metadata scope does not support 'q' parameter"

on this line
$messages = LaravelGmail::message()->unread()->preload()->all()->take(50);

{ "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "Metadata scope does not support 'q' parameter" } ], "code": 403, "message": "Metadata scope does not support 'q' parameter" } }

Store credentials for multiple users

I understand that the package is still under development but I just wanted to bring out this issue. At the moment, the credentials file is used to store credentials for only one user. You would have to logout the current user from Gmail so as to get authorization from another user. It would be great to have support for multiple users having their credentials stored in different files (or perhaps same file). This way, when using LaravelGmail::message()->using($token)->all() to specify a different token specific to the current user.

Here's a similar scenario I experienced. Let's assume we have two users, User A and User B. User A will have their token stored in the credentials file after they authorize our app with Gmail. Now when we try to get the token with LaravelGmail::makeToken() for User B without first logging out User A from Gmail, the LaravelGmail::check() method fails and so the token previously stored for User A will be used for User B. So User B ends up retrieving emails of User A.

Filter e-mails by date

Hey, how are you?

Is there a way to filter the e-mails by date like gmail allows you to? (after:, before:, older_than:, etc.).
I had a quick look at your code and I didn't saw it.

How to send an email?

Thanks again for the awesome package. I'm having troubles sending an email because I don't know what I should be instantiating it with. Current code (that doesn't work):

  $mail = LaravelGmail::message()->to($data['to'])->from('[email protected]')->subject($subject)->message($texteditor)->send();

I don't think this is it.. Haha.

Would you have any objections to having some helpers to tie it to an existing email in App\User ? I have some updated code that's working for me and I don't mind putting in a PR for it.

Batch Request ?

Using this package I am able to do What I want but while fetching gmail messages it takes lot of time to get those emails so I found out that we get message id and then using this id we have to get particular message. The reason I understood is we are making multiple call for every email and thats the reason getting emails takes lot of time. Now how do I do it using Batch Request ?

Class 'Dacastro4\LaravelGmail' Not Found

Hey

Trying to set this up in my controller but am unable to due to error when adding "use Dacastro4\LaravelGmail;" I have followed the README.md to the bone and am unable to see where i went wrong....

Using laravel version 5.6

getting gmail messages

I am trying to test this code on my controller
$messages = LaravelGmail::message()->all( $pageToken = null );
var_dump($messages);
but i get this message
Dacastro4\LaravelGmail\Services\Message and Dacastro4\LaravelGmail\Traits\SendsParameters define the same property ($params) in the composition of Dacastro4\LaravelGmail\Services\Message. However, the definition differs and is considered incompatible. Class was composed

Does anyone have have a sample controller?

I am looking for an example to get started. Especially how to use the following:

LaravelGmail::getAuthUrl Gets the URL to auth the user.

LaravelGmail::redirect You can use this as a direct method Login

LaravelGmail::logout Logs out the user

LaravelGmail::check Checks if the user is logged in

Can't login with multiple users?

I have tried setting GOOGLE_ALLOW_MULTITPLE_CREDENTIALS=true in the env file (and refreshing config cache) as well as hardcoding 'allow_multiple_credentials' => true in config/gmail.php.

But when I login as a User A in one browser, then log in as User B in a different browser, I can only see the data for User A. If I take a look at storage/app/gmail/tokens/ there's only one gmail-json file and when I open it, only the details for User A are in there.

I'm sure I'm missing something obvious here, but hoping someone can help!

$message()->preload()->all(); doesn't return all emails

Hey, I love your API, its great. However when trying to run it through all of my emails it only returns 99 instead of all of them(at this time is at 1300+). Is there a limit set somewhere that may be limiting it to 99 or is there an issue?

See below login from controller:


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use LaravelGmail;
class ReportController extends Controller
{
    
    public function mail()
    {
        $messages = LaravelGmail::message()->preload()->all();
        #return $messages[0]->payload->parts[0]->body->data;
        $subjects = $this->getSubject($messages);
        return $subjects;
    }

    //This function will loop through all of the headers to find the subject and returns the array of subjects.
    public function getSubject($messages)
    {
    	$arr = array();
    	foreach($messages as $m)
    	{
    		foreach($m->payload->headers as $h)
    		{
    			if($h->name == 'Subject')
    			{
    				array_push($arr, $h->value);
    			}
    		}

    	}
    	return $arr;
    }

    
}

I Attempted in using your take() function but it doens't seem to increase the limit...

Class 'Dacastro4\LaravelGmail' not found

I am getting the following error after following your installation steps. I have entries in the app.php in the config directory for both class and alias and I have published it as well.

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Class 'Dacastro4\LaravelGmail' not found

Also see teh following:
Symfony\Component\Debug\Exception\FatalThrowableError
โ€ฆ/app/Http/Controllers/GmailController.php15

Controller code

How Do I use Attachment Class ?

Hey I am implementing Gmail using your package but their is not much info added in this pack document. So at this point I am stuch on Attachment class it would be great if you add more info about how to use that class as I want to download attachment of an email.

Is it possible to connect automatically at the email address without user logging in ?

Hi,

I want that the connection to GMAIL at the email address (example : [email protected]) to be automatic without the user having to login ?

This email address is a common address and we have more users of the application who reply at a mail.

In fact, I want to create a ticketing application connected at GMAIL. Your program help me to receive any messages in the lavaral application.

Is it possible ?

Thanks you :)

Send Emails using Laravel Mail Facades

Hi,

How do I send emails with the views like we do using Laravel Mail Facades .
Also I am unable to figure out the how to set a user. For example I have multiple users signup with their Gmail to send mail from. I have saved the access_token and refresh_token , how do I set a user while sending emails, so the email will go from that user.

Thanks,

Class laravelgmail does not exist

Hi,

I want to configure your LaravelGmail, but I have this message on my Laravel 5.4.36 : "Class laravelgmail does not exist"

I use PHP 7.1 and your LaravelGmail in 0.4 and 0.6, the problem is the same.

I have been in my config/app.php :
Dacastro4\LaravelGmail\LaravelGmailServiceProvider::class, (provider)
'LaravelGmail' => Dacastro4\LaravelGmail\Facade\LaravelGmail::class,(aliases)

What is the problem ?

refresh token

hello dacastro4,

is there a way to have a refresh token so that the auth does not expire? i dont want to keep re-authenticating Gmail. thanks!

regards,
Joannes

Bad Aliases

I think aliases is wrong ๐Ÿ‘Ž

'aliases' => [
'Twitter' => Dacastro4\LaravelGmail\Facades\LaravelGmail::class,
]

InvalidArgumentException in Client.php line 433: Invalid token format

Hello! Help me pls!

  1. Can't understand how to modify the config file config/gmail.php.
    What to do inside of it?
    project id,client id,client secret and redirect I set in .env file.
    Is it necessary to do something with this string โ†“ ?
    'credentials_file_name' => env( 'GOOGLE_CREDENTIALS_NAME', 'gmail-json' ),

  2. I downloaded .json credentials file from google console, pasted it to:
    "[my project]/storage/app/gmail/tokens"
    then I renamed it to: 'gmail-json.json'
    Is it right?

I get error "Invalid token format"

First, congrats for you class!

I get an error "Invalid token format". I put the credentials json into storage/app/gmail/tokens/gmail-json.json with this format:

{ "installed": { "client_id": "xxxxx", "project_id": "xxxxx", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://www.googleapis.com/oauth2/v3/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_secret": "xxxxxx", "redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob", "http://localhost" ] } }

Is possible to use this package with user service account credentials file?

Thanks in advance.
Regards.

Sergio

getBody on null

I found great use of your package however the function getBodyPart() in the file Services/Messages/mail.php line 350 has the option to return null to a function which later calls getBody() on the returned value. And if you call getBody on null it throws a fatal error.

I found that only messages from icloud causes this problem since gmail's own library sets the body (plaintext) in the payload object rather than in a part.

As you can see in the images below, one email object does not have parts, it was recieved from an icloud account and the second from a gmail account, however i have tried with yahoo, hotmail and privately hosted mail servers aswell, and those work.

A suggestion is to do a check first to see if the payload has parts to begin with, and if not extract the data from the payload body itself.

withparts
withoutpart

Reply to existing messages

Here is my code

public function inbox(){
$messages = LaravelGmail::message()->unread()->preload()->all();

        foreach ( $messages as $message ) {
        $subject = $message->getSubject();
        $body = $message->getPlainTextBody();
        $fromname= $message->getFromName();
        $fromemail= $message->getFromEmail();
        
        $mail =$message ->markAsRead();
        $mail=$message ->reply('recieved')->send();

I get an error

"invalidArgument", "message": "Recipient address required" } ], "code": 400, "message": "Recipient address required" } }

How Do I draft an Email

Hey I couldn't find the option for drafting the gmail message. Could you please guide me through this.
Also Please explain how do I use Attachment Class as not much info is mentioned in your repo. Thank You

Attachment Filename

Hi there and thank you for this wrapper.
Is there a way to set the shown filename for a file i attach to a new email?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.