GithubHelp home page GithubHelp logo

webklex / laravel-imap Goto Github PK

View Code? Open in Web Editor NEW
619.0 31.0 178.0 485 KB

Laravel IMAP is an easy way to integrate both the native php-imap module and an extended custom imap protocol into your Laravel app.

Home Page: https://www.php-imap.com

License: MIT License

PHP 100.00%
laravel php imap library laravel-imap php-imap imap-library oauth idle

laravel-imap's Introduction

IMAP Library for Laravel

Latest release on Packagist Latest prerelease on Packagist Software License Code quality Total Downloads Hits Discord Snyk

Description

Laravel IMAP is an easy way to integrate both the native php-imap module and an extended custom imap protocol into your Laravel app. This enables your app to not only respond to new emails but also allows it to read and parse existing mails and much more.

Official documentation: php-imap.com/frameworks/laravel

Discord: discord.gg/jCcZWCSq

Table of Contents

Documentations

Compatibility

Version PHP 5.6 PHP 7 PHP 8
v5.x / / X
v4.x / X X
v3.x / X /
v2.x X X /
v1.x X / /

Installation

This library requires the mbstring php module. Make sure to install or enable it if it isn't available.

sudo apt-get install php*-mbstring

Installation via composer:

composer require webklex/laravel-imap

Additional information such as troubleshooting, legacy support and package publishing can be found here: php-imap.com/frameworks/laravel/installation

Basic usage example

This is a basic example, which will echo out all Mails within all imap folders and will move every message into INBOX.read. Please be aware that this should not be tested in real life and is only meant to gives an impression on how things work.

/** @var \Webklex\PHPIMAP\Client $client */
$client = Webklex\IMAP\Facades\Client::account('default');

//Connect to the IMAP Server
$client->connect();

//Get all Mailboxes
/** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */
$folders = $client->getFolders();

//Loop through every Mailbox
/** @var \Webklex\PHPIMAP\Folder $folder */
foreach($folders as $folder){

    //Get all Messages of the current Mailbox $folder
    /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
    $messages = $folder->messages()->all()->get();
    
    /** @var \Webklex\PHPIMAP\Message $message */
    foreach($messages as $message){
        echo $message->getSubject().'<br />';
        echo 'Attachments: '.$message->getAttachments()->count().'<br />';
        echo $message->getHTMLBody();
        
        //Move the current Message to 'INBOX.read'
        if($message->move('INBOX.read') == true){
            echo 'Message has ben moved';
        }else{
            echo 'Message could not be moved';
        }
    }
}

Sponsors

Feline

Known issues

Error Solution
Kerberos error: No credentials cache file found (try running kinit) (...) Uncomment "DISABLE_AUTHENTICATOR" inside and use the legacy-imap protocol config/imap.php

Support

If you encounter any problems or if you find a bug, please don't hesitate to create a new issue. However please be aware that it might take some time to get an answer.

Off topic, rude or abusive issues will be deleted without any notice.

If you need immediate or commercial support, feel free to send me a mail at [email protected].

A little notice

If you write source code in your issue, please consider to format it correctly. This makes it so much nicer to read
and people are more likely to comment and help :)

```php

echo 'your php code...';

```

will turn into:

echo 'your php code...'; 

Features & pull requests

Everyone can contribute to this project. Every pull request will be considered but it can also happen to be declined.
To prevent unnecessary work, please consider to create a feature issue
first, if you're planning to do bigger changes. Of course you can also create a new feature issue if you're just wishing a feature ;)

Change log

Please see CHANGELOG for more information what has changed recently.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

laravel-imap's People

Contributors

alfonsobries avatar ascweb avatar bastianjoel avatar carlklein avatar dansleboby avatar eidng8 avatar emtudo avatar flashws avatar freescout-helpdesk avatar gareth-ib avatar geosot avatar girvydas avatar hokan22 avatar k9uma avatar klswcz avatar koenhoeijmakers avatar limman avatar lomotech avatar madbob avatar medboubazine avatar mordisacks avatar parshikov avatar radicalloop avatar siriuo avatar sparavalo avatar thanhsonitnic avatar tiacardoso avatar todorowww avatar wagonza avatar webklex avatar

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-imap's Issues

getMessages() could be very slow...

i am using Gmail account to retrieve emails.

getting folders is slow too , but getting messages is unacceptable , and it causes laravel crash....

i have only 200 emails in my folder

getAttachments returns nothing

Hi,

I noticed a bug in the fetchAttachments method in Message class.
The "filename" attribute sometimes is not lowercase, and you use '==' (case sensitive) comparison in these if statments (line 414, line 423).
You should use strcasecmp() which is a case-insensitive string comparison.

Example:
if (!strcasecmp($parameter->attribute, "filename"))

Can not authenticate to IMAP server: [CLOSED] IMAP connection broken (authenticate)

Hi,

I'm running into this issue and I'm not sure what exactly goes wrong.

So I'm using this package to read the inbox of a certain mailbox. My script loops over every message that has been sent to the mailbox and then processes it (delete msg if not recognized or put into database if subject is known and if sender host is known).

I'm using a cronjob for this together with Laravels scheduler. The cronjob calls "\Illuminate\Support\Facades\Artisan::call('schedule:run');" every minute. In the schedule I have $schedule->command('support:process-inbound-emails')->everyMinute();

The script works perfect, but sometimes (at random times) I get following error in my errorlogs:

Couldn't open stream {imap.mailprotect.be:143/imap}. Can not authenticate to IMAP server: [CLOSED] IMAP connection broken (authenticate)

The script runs 24/7, every minute. So basically 1440 (24*60) times a day. Out of 1440, it fails 'only' 7 to 30 times with the error mentioned above.

Does anyone know what could be the cause of this error?

Unable to get folders

Hi!

Great library, seems to do what I need very well :)

Just wanted to let you know, that i get error while trying to get all folders from Office 365.

Here's my test code:

$oClient = \Webklex\IMAP\Facades\Client::account('default');
$oClient->connect();
$aMailboxes = $oClient->getFolders();

Result:

"Invalid argument supplied for foreach()" in Client.php (line 232).

I tracked down the "bug" to this recursive function on line 236:
$children = $this->getFolders(true, $pattern);

2 of my folders go that part of the scripts what are:

  • Conversation History/%
  • Yhteystiedot/%

If I skip both of them in items loop, everything works fine.

Unfortunately I was not able to figure out how to fix it.

imap_expunge(): supplied resource is not a valid imap resource

Hi,

message->delete runs imap_expunge which should not run until connection is shut down. See comments from http://php.net/manual/en/function.imap-expunge.php

Message.php:

/**
* Delete the current Message
*
* @return bool
*/
public function delete(){
$status = imap_delete($this->client->connection, $this->uid, $this->fetch_options);
$this->client->expunge(); <-- Remove
return $status;
}

Add new function for Client.php to delete all messages marked for delete (which is done through imap_delete).

[15-Nov-2017 15:21:21 UTC] PHP Fatal error: Uncaught ErrorException: imap_expunge(): supplied resource is not a valid imap resource in /www/vendor/webklex/laravel-imap/src/IMAP/Client.php:448
Stack trace:
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'imap_expunge():...', '/www...', 448, Array)
#1 /www/vendor/webklex/laravel-imap/src/IMAP/Client.php(448): imap_expunge(Resource id #307)
#2 /www/vendor/webklex/laravel-imap/src/IMAP/Client.php(211): Webklex\IMAP\Client->expunge()
#3 /www/vendor/webklex/laravel-imap/src/IMAP/Client.php(102): Webklex\IMAP\Client->disconnect()
#4 [internal function]: Webklex\IMAP\Client->__destruct()
#5 {main}
thrown in /www/vendor/webklex/laravel-imap/src/IMAP/Client.php on line 448

Pagination

Is there a way to paginate the messages of the mailboxes?
For example Getting a larger inbox like outlook or gmail?

Unable to save Email attachments (Outlook .msg files)

Hi,

I use this package to successfully deal with many tens of email on daily basis. So far I was able to extract almost all attachments: pdf files, excel files etc. However, I was never able to extract email attachment (Outlook .msg file) from the message. Almost all users of the app I am building are using Microsoft Outlook desktop application to send their emails and they often attach another email (previously stored) to the message (usually .msg extension).

Any idea how to save such attachment (.msg file) to drive? Thanks.

How to sent mail ?

I am not able to send imap mail, is there any method to send mail using this package ?

FT_PEEK not working

Hi,
Thanks for the Package. But when i try to get messages using getMessages() function using ft_peek, because i don't want my messages to be set as read. but i get error while using this.
Code:
$message=$oClient->getMessages($this->aMailboxes[0],'ALL',FT_PEEK);

(1/1) GetMessagesFailedExceptionimap_fetchheader(): invalid value for the options parameter

in Client.php (line 320)
at Client->getMessages(object(Folder), 'ALL', 2)

Email bodies not fetching

Everything was working smoothly before the optional config parameter was added. Now email bodies won't fetch and all I get is an empty array. Is there anything special that needs to be done with this new changes?

Undefined Variable

Hi, I followed the instructions from readme file, step by step, and I get the following error: Undefined variable: oMailbox

I'm using Laravel 5,6

captura

Here's my code:

`public function inbox(){

    $oClient = new Client([
	    'host'          => 'imap.gmail.com',
	    'port'          => 993,
	    'encryption'    => 'ssl',
	    'validate_cert' => true,
	    'username'      => '[email protected]',
	    'password'      => 'mypassword',
	]);

	//Connect to the IMAP Server
	$oClient->connect();

	//Get all Mailboxes
	/** @var \Webklex\IMAP\Support\FolderCollection $aFolder */
	$aFolder = $oClient->getFolders();

	//Loop through every Mailbox
	/** @var \Webklex\IMAP\Folder $oFolder */
	foreach($aFolder as $oFolder){

	    //Get all Messages of the current Mailbox
	    /** @var \Webklex\IMAP\Support\MessageCollection $oMessage */
	    $aMessage = $oMailbox->getMessages();
	    
	    /** @var \Webklex\IMAP\Message $oMessage */
	    foreach($aMessage as $oMessage){
	        echo $oMessage->subject.'<br />';
	        echo 'Attachments: '.$oMessage->getAttachments()->count().'<br />';
	        //echo $oMessage->getHTMLBody(true);
	        
	        //Move the current Message to 'INBOX.read'
	        if($oMessage->moveToFolder('INBOX.read') == true){
	            echo 'Message has ben moved';
	        }else{
	            echo 'Message could not be moved';
	        }
	    }
	}
}

`

how to open folder INBOX

I don't really understand the openFolder part of the documentation.
How do I open a folder with the name INBOX?

Error: Undefined property: stdClass::$disposition

My first try with this (in Laravel 5.4)...
Names of folders is working so connection is okay.
But if I want to retrieve messages it gives an error:
GetMessagesFailedException in Client.php line 310:
Undefined property: stdClass::$disposition

My code:

$oClient = Webklex\IMAP\Facades\Client::account('default');
$oClient->connect();

$aMailboxes = $oClient->getFolders();
foreach($aMailboxes as $oMailbox){
echo '<br><br>'.$oMailbox->name.'<br>';
    foreach($oMailbox->getMessages() as $oMessage){
        echo $oMessage->subject.'<br />';
    } 
} 

Problem installing package on Laravel 5.3

Problem 1
- Installation request for webklex/laravel-imap 1.0.2.12 -> satisfiable by webklex/laravel-imap[1.0.2.12].
- Conclusion: remove nesbot/carbon 1.21.0
- Conclusion: don't install nesbot/carbon 1.21.0
- webklex/laravel-imap 1.0.2.12 requires nesbot/carbon ^1.22 -> satisfiable by nesbot/carbon[1.22.0, 1.22.1].
- Can only install one of: nesbot/carbon[1.22.0, 1.21.0].
- Can only install one of: nesbot/carbon[1.22.1, 1.21.0].
- Installation request for nesbot/carbon (locked at 1.21.0) -> satisfiable by nesbot/carbon[1.21.0].

imap_open(): Couldn't open stream {imap.gmail.com:993/imap}

Laravel 5.2
I have a command that fetches email I get the error imap_open(): Couldn't open stream

use Webklex\IMAP\Facades\Client ;

public function handle() {

        /*
	    .env settings		
            IMAP_HOST=imap.gmail.com
            IMAP_PORT=993
            IMAP_ENCRYPTION=tls
            IMAP_VALIDATE_CERT=true
            [email protected]
            IMAP_PASSWORD=mypassword
            IMAP_DEFAULT_ACCOUNT=default
        */
        $oClient = new Client([
            'host'          => env('IMAP_HOST'),
            'port'          => env('IMAP_PORT'),
            'encryption'    => env('IMAP_ENCRYPTION'),
            'validate_cert' => env('IMAP_VALIDATE_CERT'),
            'username'      => env('IMAP_USERNAME'),
            'password'      => env('IMAP_PASSWORD'),
        ]);

        $oClient = Client::account('default');

        //Connect to the IMAP Server
        $oClient->connect();

$oClient->connect(); returns this error:

  [Webklex\IMAP\Exceptions\ConnectionFailedException]                                                             
  imap_open(): Couldn't open stream {imap.gmail.com:993/imap}. [CLOSED] IMAP connection broken (server response)  

I appreciate any help, thanks.

imap_fetch_overview needed

Actually this is not a issue , more like an request .

Retrieve all the messages in a folder could be slow , is it possible to add a fetch overview method to get all the subjects , date , from , to ,etc ? This could speed up the reading.

also , once click on the message , we need to access the specific mail , how to do it ?

if the emails are like a database model , we could do everything laravel provided , but since it is not .....

THANKS , anyone has good thoughts , please share !

Message automaticly set to "read"

Hi,

Actually i do that

public function index() { $oUnseenMsgs = $this->oClient->getUnseenMessages($this->oClient->getFolder('INBOX')); return view('dashboard', compact('oUnseenMsgs')); }

And if i jst refreh my app, my emails status change to "read" automaticly, why?

P.S: i use OVH smtp

Confusing default configuration values

The library assumes that there will exist a default account, and that account must have all properties configured.

In particular I tried to use this configuration:


    'accounts' => [
        'default' => [
            'port' => 993,
            'encryption' => 'tls',
            'validate_cert' => true,
        ],
        'grappling' => [
            'host' => 'mail.example.com',
            'username' => '[email protected]',
            'password' => env('IMAP_GRAPPLING_PASSWORD', null),
        ],
    ],

But in Client::setConfig only configuration properties from the default account will ever be set.

Expected behavior is that all the values from both grappling are used, with default values from default.

How can I specify a single folder?

Hello,
I can get all folders through $client->getFolders() , but if I would like to specify a single one, example INBOX, how can I do for it? like this: foreach the mailboxes and then judge the condition if ($mailbox->name === 'INBOX') ? pls give me some advise!

look forward your reply, thanks in advance

Laravel 5.4.*

Hello this plugin work with with Laravel 5.4?

I got this message:

Your requirements could not be resolved to an installable set of packages.

Problem 1
- webklex/laravel-imap 1.0.0 requires laravel/framework ~5.2.0 -> satisfiable by laravel/framework[5.2.x-dev].
- webklex/laravel-imap 1.0.1 requires laravel/framework ~5.2.0 -> satisfiable by laravel/framework[5.2.x-dev].
- webklex/laravel-imap 1.0.x-dev requires laravel/framework ~5.2.0 -> satisfiable by laravel/framework[5.2.x-dev].
- Conclusion: don't install laravel/framework 5.2.x-dev
- Installation request for webklex/laravel-imap ^1.0 -> satisfiable by webklex/laravel-imap[1.0.0, 1.0.1, 1.0.x-dev].

Create an option to avoid that the fetched messages marked as read

In the function "fetchStructure" in Message.php (line 308), especifically when you use the imap_fetchbody you have the fourth argument (options) with the value "FT_UID", that's the default option and works fine but mark the fetched messages as read, that in some cases (like me) it's not what you want.

According to the documentation if you instead use the flag FT_PEEK the message wasn't marked as read.

I think that will be great if you make this option configurable, in my case i need that the messages doesn't mark as read.

´´´
//imap_fetchbody($this->client->connection, $this->uid, $partNumber, FT_UID);
imap_fetchbody($this->client->connection, $this->uid, $partNumber, FT_PEEK);
´´´

http://php.net/manual/es/function.imap-fetchbody.php

Can I use this library for Lumen 5.5?

I am using Lumen 5.5, where I need to use IMAP to load emails from the client.
In Composer.json

"require": {
"php": ">=5.5.9",
"laravel/framework": ">=5.0.0"
},

Larvel framework is required, Can I change this to "laravel/lumen" : ">=5.0.0" and will that work ok in the Lumen framework?

Exception Parse Data

Hello, I'm getting this exception

error-email-imap

I added a try in the parse header function in the message class to pass the error.

private function parseHeader() {
$header = imap_fetchheader($this->client->connection, $this->uid, $this->fetch_options);
if ($header) {
$header = imap_rfc822_parse_headers($header);
}

if (property_exists($header, 'subject')) {
    $this->subject = imap_utf8($header->subject);
}
if (property_exists($header, 'date')) {
    try{
        $this->date = Carbon::parse($header->date);
    }catch (\Exception $e){
    }
}
if (property_exists($header, 'from')) {
    $this->from = $this->parseAddresses($header->from);
}
if (property_exists($header, 'to')) {
    $this->to = $this->parseAddresses($header->to);
}
if (property_exists($header, 'cc')) {
    $this->cc = $this->parseAddresses($header->cc);
}
if (property_exists($header, 'bcc')) {
    $this->bcc = $this->parseAddresses($header->bcc);
}

if (property_exists($header, 'reply_to')) {
    $this->reply_to = $this->parseAddresses($header->reply_to);
}
if (property_exists($header, 'sender')) {
    $this->sender = $this->parseAddresses($header->sender);
}

if (property_exists($header, 'message_id')) {
    $this->message_id = str_replace(['<', '>'], '', $header->message_id);
}
if (property_exists($header, 'Msgno')) {
    $this->message_no = ($this->fetch_options == FT_UID) ? trim($header->Msgno) : imap_msgno($this->client->getConnection(), trim($header->Msgno));
}

}

Cant show Gmail messages

When i try to use $oMailbox->getMessages() with a Gmail account on localhost the conection is lost and laravel stop. I have to kill some PHP process to can run php artisan serve again. Can somebody help?

getMessageNo() is empty?

When looping through a series of messages in a folder, I can get the UUID, subject, etc. but when I access the 'getMessageNo()' it's empty.

Is there any reason for this or a bug perhaps?

how to use getFrom

Hello, I dont understand how to use from or getFrom.

Here is my code:
foreach($aMailboxes as $oMailbox){
foreach($oMailbox->getMessages() as $oMessage){
echo $oMessage->from.' '.$oMessage->subject.'<br />';
}
}

but always getting error: Array to string conversion

timeout issue after 60 sec

My code is below

// Replace with your Test Function
$oClient = new Client();
//Connect to the IMAP Server
$oClient->connect();

        //Get all Mailboxes
        $aMailboxes = $oClient->getFolders(false,'INBOX');

        //Loop through every Mailbox
        /** @var \Webklex\IMAP\Folder $oMailbox */
        
        foreach($aMailboxes as $oMailbox){
            //Get all Messages of the current Mailbox
            /** @var \Webklex\IMAP\Message $oMessage */
            $count = 0;
            foreach($oMailbox->getMessages() as $oMessage){
                
                echo $oMessage->subject.'<br />';
                echo 'Attachments: '.$oMessage->getAttachments()->count().'<br />';
                echo $oMessage->getHTMLBody(true);

               
            if($count==1)
            {
                break;
            }
            $count++;  
                
            }
            
        }

I am getting an exception :

(1/1) FatalErrorExceptionMaximum execution time of 60 seconds exceeded

in Message.php (line 452)

I want to fetch only 1st email and show.

how can I do ?

[Help] Saving Attachments

Hi,
Not sure how people have done this basically I want my script to use each attachment and save them and send them to s3 how have people managed to save their attachments and save them in this way?

Any examples would be appreciated, thank you.

$outlook->connect();
$folder = $outlook->getFolder('Inbox');
foreach($folder->getMessages() as $message){
	$subject = $message->subject;
	$attachments = $message->getAttachments();
	dd($attachments);
	foreach($attachments as $attachment){
		$file = header('Content-type: '.$attachment->content_type.'');
		$file .= header('Content-disposition: attachment; filename='.$attachment->name.'');
		print $attachment->content;
		// send it to s3 Storage::disk('s3')->put
	}
	$message->moveToFolder('Success');
}

Use of undefined constant FT_UID - assumed 'FT_UID'

Hi there!

I just did a fresh installation of your package and encouterd the following error

Use of undefined constant FT_UID - assumed 'FT_UID'

Its comming from your package because it appears as soon as i add the package server provider. Im not doing anything with the package yet.

I hope this gives you some information.

Kinda regards,

Robert

[ErrorException] Use of undefined constant FT_UID - assumed 'FT_UID'

Hi,

I got this error
[ErrorException] Use of undefined constant FT_UID - assumed 'FT_UID' when I add your provider and alias into config\app.php inside the arrays of providers and aliases . Your document also wrongly indicate to add the provider and alias inside config/imap.php please check the document and change to config/app.php

Thanks for your contribution to the open source world.

Error with publishing

Hi I'm using laravel 5.5,

but i get the following error when i follow the installation steps in the readme. Use of undefined constant FT_UID - assumed 'FT_UID'

$folder->appendMessage stop request

HI,

I have this :

$messageStruct = $this->build_mime_msg($recipient,$subject,$content,"[email protected]");
$this->oClientRead->getFolder('INBOX.INBOX.Sent')->appendMessage($messageStruct);
return redirect()->route('webmail.inbox')->with(['email-success' => 'L\'email a bien été envoyé.']);`

screenshot_20180209_115555

The mail is correctly save on sent folder but my Post request return anything. I don't understand why.

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.