Coder Social home page Coder Social logo

benhall14 / php-imap-reader Goto Github PK

View Code? Open in Web Editor NEW
25.0 3.0 9.0 40 KB

A PHP class that makes working with IMAP in PHP as easy as possible.

Home Page: https://conobe.co.uk/projects/php-imap-reader

License: MIT License

PHP 100.00%
imap-client php imap

php-imap-reader's Introduction

PHP IMAP Reader

A PHP class that makes working with IMAP as easy as possible.

This class is written to be chain-able so to create a logically fluent and easily readable way to access an IMAP mailbox.

It simplifies the PHP IMAP_* library into a set of easy to read methods that do the heavy lifting for you.

It has been fully tested to work with PHP 5.3+, including PHP 8.1.

Installation via Composer

You can now install this class via composer.

$ composer require benhall14/php-imap-reader

Remember to add the composer autoloader before using the class and use the correct namespace.

require 'vendor/autoload.php';

use benhall14\phpImapReader\Email as Email;
use benhall14\phpImapReader\EmailAttachment as EmailAttachment;
use benhall14\phpImapReader\Reader as Reader;

Usage

Please make sure you have added the required classes.

In its simplest form, use the following to connect:

define('IMAP_USERNAME', ''); 				# your imap user name
define('IMAP_PASSWORD', ''); 				# your imap password
define('IMAP_MAILBOX', ''); 				# your imap address EG. {mail.example.com:993/novalidate-cert/ssl}
define('ATTACHMENT_PATH', __DIR__ . '/attachments'); 	# the path to save attachments to or false to skip attachments

try{
    
    # set the mark as read flag (true by default). If you don't want emails to be marked as read/seen, set this to false.
    $mark_as_read = true;

    # You can ommit this to use UTF-8 by default.
    $encoding = 'UTF-8'

    # create a new Reader object
    $imap = new Reader(IMAP_MAILBOX, IMAP_USERNAME, IMAP_PASSWORD, ATTACHMENT_PATH, $mark_as_read, $encoding);

    # use one or more of the following chain-able methods to filter your email selection
    $imap
        ->folder($folder)           # alias for mailbox($mailbox)
        ->mailbox($mailbox)         # sets the mailbox to return emails from. Default = INBOX
        ->id($id)                   # retrieve a specific email by id
        ->recent()                  # get all RECENT emails
        ->flagged()                 # get all FLAGGED emails
        ->unflagged()               # get all UNFLAGGED emails
        ->unanswered()              # get all UNANSWERED emails
        ->deleted()                 # get all DELETED emails
        ->unread() 		    # alias for UNSEEN()
        ->unseen()                  # get all UNSEEN emails
        ->from($email)              # get all emails from $email
        ->searchSubject($string)    # get all emails with $string in the subject line
        ->searchBody($string)       # get all emails with $string in the body
        ->searchText($string)       # get all emails with $string TEXT
        ->seen()                    # get all SEEN emails
        ->read() 		    # alias for SEEN()
        ->newMessages()             # get all NEW emails
        ->oldMessages()             # get all OLD emails
        ->keyword($keyword)         # get all emails with $keyword KEYWORD
        ->unkeyword($keyword)       # get all emails without $keyword KEYWORD
        ->beforeDate($date)         # get all emails received before $date. *Date should be in a format that can be parsed by strtotime.*
        ->sinceDate($date)          # get all emails received since $date. *Date should be in a format that can be parsed by strtotime.*
        ->sentTo($to)               # get all emails sent to $to
        ->searchBCC($string)        # get all emails with $string in the BCC field
        ->searchCC($string)         # get all emails with $string in the CC field
        ->onDate($date)             # get all emails received on $date. *Date should be in a format that can be parsed by strtotime.*
        ->limit($limit)             # limit the number of emails returned to $limit for pagination
        ->page($page)               # used with limit to create pagination
        ->orderASC()                # order the emails returned in ASCending order
        ->orderDESC()               # order the emails returned in DESCendeing order
        ->reset()                   # resets the current reader to be able to reconnect to another folder/mailbox.
        ->all()                     # get all emails (default)
        ->get();                    # finally make the connection and retrieve the emails.
    
    # You can then loop through $imap->emails() for each email.
    foreach($imap->emails() as $email){

        # The email has been clean and formated.
        # see below.

    }

    # Reset the reader and connect to another folder.
    $imap->reset()->folder('Sent')->get();

    # You can also create a folder/mailbox on the IMAP stream.
    $imap->createFolder('New Folder Name');
    #or 
    $imap->createMailbox('New Folder Name');

    # You can also check if a mailbox/folder exists on the IMAP stream using:
    if ($imap->doesMailboxExists('INBOX')) {
        return "Yes, it exsits";
    } else {
        return "No, it doesn't exist.";
    }
    
    # ... your code here ...

} catch (Exception $e){

    echo $e->getMessage();

}

While looping through the returned emails, each email object can be used as below:

    $email->isTo('[email protected]');   # Return true if the email is to $email, else returns false

    $email->replyTo();              	# Returns an array of Reply To email addresses (and names)

    $email->cc();                 	# Returns an array of CC email addresses (and names)

    $email->to();                       # Returns the recipient email address

    $email->id();                       # Returns the id of the email

    $email->size();                     # Returns the size of the email

    $email->date($format);        	# Returns the date in the $format specified. Default Y-m-d H:i:s

    $email->subject();          	# Returns the email subject

    $email->fromName();     		# Returns the sender's name, if set.

    $email->fromEmail();     		# Returns the sender's email address

    $email->plain();            	# Returns the plain text body of the email, if present

    $email->html();            		# Returns the html body of the email, if present

    $email->hasAttachments();       	# Returns true/false based on if the email has attachments

    $email->attachments();      	# Returns an array of EmailAttachment objects

    $email->attachment($id);    	# Returns an attachment based on the given attachment $id

    $email->isRecent();   		# Returns true/false based on the recent flag

    $email->isUnseen();       		# Returns true/false based on the unseen flag

    $email->isFlagged();  		# Returns true/false based on the flagged flag

    $email->isAnswered(); 		# Returns true/false based on the answered flag

    $email->isDeleted();      		# Returns true/false based on the deleted flag

    $email->isDraft();          	# Returns true/false based on the draft flag

    $email->eml();                      # Returns the email in .eml format

    $email->saveEml($filename);         # Saves the email in .eml format
    
    $email->count();         # Returns number of emails in folder

The $email->attachments(); method returns an array of attachments belonging to the email in a benhall14\phpImapReader\EmailAttachment object. The following methods are available for each attachment.

	# check if the current $email has any attachments.
	if($email->hasAttachments()){
	
		# get the attachments for the current $email in the	loop.
		$attachments = $email->attachments();
	
		# loop through the found attachments.
		foreach($attachments as $attachment){

			$attachment->id(); 			# Returns the attachments ID.

			$attachment->name(); 		    	# Returns the attachments name.

			$attachment->filePath(); 		# Returns the local file path for the attachment. This is based on the ATTACHMENT_PATH constant set in the imap config.

			$attachment->content();			# Returns the attachments content data.

			$attachment->type(); 			# Returns either 'attachment' or 'inline'.

		}

}	

Requirements

Works with PHP 5.3+ (including PHP 8.1)

PHP IMAP Extension

License

Copyright (c) 2016-2021 Benjamin Hall, [email protected] https://conobe.co.uk

Licensed under the MIT license

Donate?

If you find this project helpful or useful in anyway, please consider getting me a cup of coffee - It's really appreciated :)

Donate

php-imap-reader's People

Contributors

benhall14 avatar mertuarez avatar waterleat 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

Watchers

 avatar  avatar  avatar

php-imap-reader's Issues

Create Mailbox?

Hi,

it would be great, if this class would also support creating new mailboxes/folders via imap_createmailbox. Maybe including the possibility to determine, if the given mailbox/folder already exists.

Problem with get all attachments and display images inside mail

Hi, I use your class from few days and I saw a little problem.

I have mail with 4 .html attachments and two images inside message.

And When I list attachments throught your class is showing me only 3 attachements but inside are two gifs (images from message) and one html file.

When I use method html message is empty but when i get plain is getting message but without that images.

I got another mail but with 4 .xls files and 2 images inside message and its the same problem in attachments are only two images and one xls file.

And second it is possible to detect encoding of attachments? Because I saw that in mails for each attachment it could be different encoding and from time to time when class save attachments theirs names are wrong.

Fatal error: Uncaught ErrorException: Creation of dynamic property benhall14\phpImapReader\Reader::$encoding is deprecated in /var/www/html/vendor/benhall14/php-imap-reader/src/phpImapReader/Reader.php on line 145

Fatal error: Uncaught ErrorException: Creation of dynamic property benhall14\phpImapReader\Reader::$encoding is deprecated in /var/www/html/vendor/benhall14/php-imap-reader/src/phpImapReader/Reader.php on line 145

Tried to create Reader instance like this:

use benhall14\phpImapReader\Reader;

$imap = new Reader(
    $_ENV['IMAP_SERVER'],
    $_ENV['IMAP_LOGIN'],
    $_ENV['IMAP_PASSWORD'],
    mark_as_read: false
);

And as I see, there really is no $encoding field in the Reader class. Fix it please.

Plz add imap_expunge to Reader.php

Please add this to Reader.php:

public function expunge()
{
    return imap_expunge($this->stream());

}

without it there is no way that messages that are marked for delete are really deleted.

Needs another stable version tag

Running composer with stable settings to clone version 1.0 will retrieve files with the old folder naming. I recommend you release a new version that includes commit 476c21c to include the new folder naming.

Method to download whole email as .eml

I love this class and I have a particular use case that involves me saving a copy of the email in eml format (headers and body) to the local disk. Is this possible? I cant see a way looking through the code.

Issue with PHP function:count() when no value is used with limit()

I hadn't noticed this before until just now. The error is thrown if limit() has no value assigned to it. Or it isn't used at all with get().

[06-May-2019 23:55:41 Australia/Hobart] PHP Warning: count(): Parameter must be an array or an object that implements Countable in /var/www/LibreCMS/core/imapreader/Reader.php on line 678`

Base64 Decode

Hi, thanks for a great little imap parser, I'm using it in my LibreCMS project in my webmail part of the CMS. However, I've discovered some emails that are received have the body encoded with a base64 encoding.

I've had a look through your source, and it looks as though you have an imap_base64 in the receiving part of the script. Should it be decrypting base64 or base8 decryped emails? I tried to check if you have a check to do so, but couldn't find it. I could easily store a flag in my database to indicate the type of encoding, but I need to be able to tell which meissages are encoded, and which aren't.

Again, thanks for making the script, it's easy to use, and works great for my purposes.

Mark as read issue

$email->setRawBody(imap_fetchbody($this->stream(), $uid, '', FT_UID));

This should not also mark as read
$email->setRawBody(imap_fetchbody($this->stream(), $uid, '', FT_UID | FT_PEEK));

So has to follow flags
$email->setRawBody(imap_fetchbody($this->stream(), $uid, '', $options));

No emails triggers error

This occurs when the email object has no entries:

Warning: count(): Parameter must be an array or an object that implements Countable in /var/www/vhosts/developerbootcamp.co.uk/admin.developerbootcamp.co.uk/libs/php/phpImapReader/Reader.php on line 802

Unable to get attachment files when no attachment folder is set

Hi,
I'm using phpImapReader to pull in attached files from an email account. I wasn't able to get the EmailAttachment->contents to work.
It looks like the issue is in line 1237 of the Reader.php file.
$attachment->setAttachmentContent($data) is commented out.

I replaced it with:

$attachement->setAttachmentData($data)

That seems to work.

Regards,
Greg

exampel

Help and example example for using single email mode with id.

$imap = new Reader(IMAP_MAILBOX, IMAP_USERNAME, IMAP_PASSWORD, ATTACHMENT_PATH); 
$imap
->id($_GET['em'])	
->get();		
foreach ($imap->emails() as $email) {
    echo 'SUBJECT: '.$email->subject().'<br/>';		
    echo 'SENDER: '.$email->fromEmail();                  
    echo '  --- '.$email->date('Y-m-d H:i');
	echo '<hr/>'.$email->plain();
    echo '<hr/>';
}

not show!

imap_list

hi Benjamin,
i can`t find imap_list.

Method to move mails

I added this and works perfect for me using your library. THANKS A LOT!!

/**
   * Move mail to specific folder
   * @param  string $folder Destination folder
   * @param  int $email_id The id of the email to move.
   * @return boolean       The result of the action.
   */
  public function moveEmailToFolder($folder,$email_id){
    return imap_mail_move($this->stream(), $email_id, $folder);
  }

Error during retrieve attachment

Hi, i'm trying to retrieve content data of an attachment with: $attachment->content(); but i get this error:

Warning: Undefined property: benhall14\phpImapReader\EmailAttachment::$attachment_data  ...... on line 173

if I print a var_dump i get my attachment like this:

object(benhall14\phpImapReader\EmailAttachment)[24]
  public 'id' => int 738572691
  public 'name' => string 'logo.png'
  public 'file_path' => null
  public 'type' => string 'attachment' (length=10)
  public 'mime' => null

I've set:

define('ATTACHMENT_PATH', false);

If I set:

 define('ATTACHMENT_PATH', __DIR__ . '/attachments');

I get ALL attachments to be downloaded (of all emails). My goal is to download attachments only for a specific email, searching inside the header (like my past ticket closed)... but to do my search I need to download ALL emails, then filter trought header...

Any suggest? thanks

Emails always marked as read

I've tried connecting to the mailbox using this:

$imap = new Reader(IMAP_MAILBOX, IMAP_USERNAME, IMAP_PASSWORD, false, false);

And the emails retrieve correctly, but they're always flagged as read.

I've even tried commenting out this section

if ($this->mark_as_read) {
	//$this->markAsRead($id);
}

And still they're flagged as read.

This is how I'm retrieving the emails:

$imap->unseen();
$imap->get();

Filter by custom header

Hi, is there any function to filters email by custom header? For example "References" key or any other custom ones? thanks

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.