Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6905587
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T08:12:08+00:00 2026-05-27T08:12:08+00:00

the class is provided here: <?php /** * EmailReader * * Access email from

  • 0

the class is provided here:

    <?php

    /**
    * EmailReader
    *
    * Access email from an IMAP or POP account.
    * Currenly only supports fetching attachments.
    *
    * @see http://github.com/driverdan/emailreader
    * @see http://driverdan.com
    *
    * @author Dan DeFelippi <dan@driverdan.com>
    * @license MIT
    * @todo Add additional features beyond saving attachments.
    */
class EmailReader {
// Stores mailbox stream
private $mbox;

// Email part types. Accessed via array position, do not reorder.
var $partTypes = array(
    "text",
    "multipart",
    "message",
    "application",
    "audio",
    "image",
    "video",
    "other",
);

/**
 * Constructor opens connection to the server.
 *
 * @see http://www.php.net/manual/en/function.imap-open.php
 *
 * @param string $host Host connection string.
 * @param string $user Username
 * @param string $password Password
 *
 * @return bool Returns true on success, false on failure.
 */
function __construct($host, $user, $password) {
    return (bool)($this->mbox = imap_open($host, $user, $password));
}

/**
 * Destructor closes server connection.
 */
function __destruct() {
    imap_close($this->mbox);
}

/**
 * Decodes a message based on encoding type.
 *
 * @param string $message Email message part.
 * @param int $encoding Encoding type.
 */
function decode($message, $encoding) {
    switch ($encoding) {
        case 0:
        case 1:
            $message = imap_8bit($message);
        break;

        case 2:
            $message = imap_binary($message);
        break;

        case 3:
        case 5:
            $message = imap_base64($message);
        break;

        case 4:
            $message = imap_qprint($message);
        break;
    }

    return $message;
}

/**
 * Saves all email attachments for all emails. Uses original filenames.
 *
 * @todo Handle duplicate filenames.
 *
 * @param string $path Directory path to save files in.
 * @param bool $inline Save inline files (eg photos). Default is true.
 * @param bool $delete Delete all emails after processing. Default is true.
 */
function saveAttachments($path, $inline = true, $delete = true) {
    $numMessages = $this->getNumMessages();

    // Append slash to path if missing
    if ($path[strlen($path) - 1] != '/') {
        $path .= '/';
    }

    // Loop through all messages
    for ($msgId = 1; $msgId <= $numMessages; $msgId++) {
        $structure = imap_fetchstructure($this->mbox, $msgId, FT_UID);    
        $fileNum = 2;

        // Loop through all email parts
        foreach ($structure->parts as $part) {
            // Handle attachments and inline files (images)
            if (strtoupper($part->disposition) == "ATTACHMENT" || ($inline && strtoupper($part->disposition) == "INLINE")) {
                /**
                 * File extension is determined first by MIME type.
                 * This is because some phone email clients do not use real filenames for attachments.
                 * Other phones use CONTENT-OCTET or other generic MIME type so fallback to file extension.
                 * This was designed to process images so it may not work correctly for some MIME types.
                 */
                $ext = strtolower($part->subtype);

                if (strlen($ext) > 4) {
                    $ext = end(explode('.', $part->dparameters[0]->value));
                } else if ($ext == "jpeg") {
                    $ext = "jpg";
                }
                // @TODO Add other MIME types here?

                $filename = $entry['id'] . ".$ext";

                // Get the body and decode it
                $body = imap_fetchbody($this->mbox, $msgId, $fileNum);
                $data = self::decode($body, $part->type);

                // Save the file
                $fp = fopen("$path$filename", "w");
                fputs($fp, $data);
                fclose($fp);

                $fileNum++;
            }
        }

        if ($delete) {
            $this->delete($msgId);
        }
    }

    // Expunging is required if messages were deleted
    if ($delete) {
        $this->expunge();
    }
}

/**
 * Gets the number of messages in a mailbox.
 *
 * @return int Number of messages in the mailbox.
 */
function getNumMessages() {
    return imap_num_msg($this->mbox);
}

/**
 * Deletes a message.
 *
 * @param int $id ID of message to delete.
 * @param bool $expunge Optionally expunge mailbox.
 */
function delete($id, $expunge = false) {
    imap_delete($this->mbox, $id);

    if ($expunge) {
        $this->expunge();
    }
}

/**
 * Expunge a mailbox. Call after deleting messages.
 */
function expunge() {
    imap_expunge($this->mbox);
}
 }

I am very new to dealing with mail servers, and such, so I have no clue as to how to receive email and run a PHP script with it, etc.

I think this class will help me with that, so, learning how to implement it would be great.

thanks so much!!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T08:12:08+00:00Added an answer on May 27, 2026 at 8:12 am

    To use this class you will need to ensure that PHP_IMAP extension is installed and enabled.

    If you read the comments in the code you will find that they document the use of the class quite well.

    The first thing you need to do is instantiate the class providing the constructor with the mail host, user name and password like this:-

    $emailReader = new EmailReader('imap.myhost.com', 'myUserName', 'myPassWord');
    

    After that it is just a matter of calling the methods you require. For instance, you can find out how many emails are in the mail box like this:-

    $numMessages = $emailReader->getNumMessages();
    

    I have to say though that this class does not seem to be complete or particularly well written and I would recommend looking for another class. You may find the Pear Mail Package suitable for your needs. It will certainly give you a more complete, better written code base to learn from.

    I should also warn you that I couldn’t get this class to connect to the two of my mail servers that I tried, although I didn’t try for very long.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have looked at many questions here (and many more websites) and some provided
After my hosting provider upgraded server (Debian) and PHP (from 5.2.6 to 5.3.2) I
Here's the question first: Is this possible? I'm taking my inspiration from Joe Wrobel's
PHP mysql database I have created a follow on question to this one here
I am implementing the rating stars provided here Rating Stars , and I am
For my project I wrote a small config class that loads its data from
I'm creating an ORM in PHP, and I've got a class 'ORM' which basically
I have the following form in cakephp: <div class=quickcontactDisplay> <?php echo $form->create('Enquiry',array('action'=>'add','class'=>'quickcontact')); echo $form->hidden('visitor_id',
I have a project that needs to access a DLL with PHP. The server
I'm trying to create a oauth provider using PHP and it's official oauth class.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.