How to pull emails from my server with PHP

Asked

Viewed 1,330 times

1

I would like to know how to pull my emails from my POP3 server to a PHP page, that is, pull and display all emails, as outlook does, only I would like to know how to do this with PHP. I searched a lot about it and didn’t find it. I will pull from a domain of my own.

  • 1

    Imap would be better. It does not have this possibility ?

  • Marcelo Bezerra’s answer has something very simple. But to create an email client is very complex. You may want to use something already ready as the roundcube: http://roundcube.net/.

1 answer

1

You can use Imap functions

Example: http://garrettstjohn.com/entry/reading-emails-with-php/

<?php
class Email_reader {
    // imap server connection
    public $conn;
    // inbox storage and inbox message count

    private $inbox;
    private $msg_cnt;

    // email login credentials
    private $server = 'yourserver.com';
    private $user   = '[email protected]';
    private $pass   = 'yourpassword';

    private $port   = 143; // adjust according to server settings

    // connect to the server and get the inbox emails
    function __construct() {
        $this->connect();
        $this->inbox();
    }

    // close the server connection
    function close() {
        $this->inbox = array();
        $this->msg_cnt = 0;

        imap_close($this->conn);
    }

    // open the server connection
    // the imap_open function parameters will need to be changed for the particular server
    // these are laid out to connect to a Dreamhost IMAP server

    function connect() {
        $this->conn = imap_open('{'.$this->server.'/notls}', $this->user, $this->pass);
    }

    // move the message to a new folder
    function move($msg_index, $folder='INBOX.Processed') {

        // move on server
        imap_mail_move($this->conn, $msg_index, $folder);
        imap_expunge($this->conn);

        // re-read the inbox
        $this->inbox();
    }

    // get a specific message (1 = first email, 2 = second email, etc.)
    function get($msg_index=NULL) {
        if (count($this->inbox) <= 0) {
            return array();
        }
        elseif ( ! is_null($msg_index) && isset($this->inbox[$msg_index])) {
            return $this->inbox[$msg_index];
        }
        return $this->inbox[0];
    }

    // read the inbox
    function inbox() {
        $this->msg_cnt = imap_num_msg($this->conn);
        $in = array();

        for($i = 1; $i <= $this->msg_cnt; $i++) {
            $in[] = array(
                'index'     => $i,
                'header'    => imap_headerinfo($this->conn, $i),
                'body'      => imap_body($this->conn, $i),
                'structure' => imap_fetchstructure($this->conn, $i)
            );
        }

        $this->inbox = $in;
    }
}

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.