<?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;
private $user;
private $pass;
private $port;
// connect to the server and get the inbox emails
function __construct($server,$user,$pass,$port=143) {
$this->server=$server;
$this->user=$user;
$this->pass=$pass;
$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);
}
// return true if connect() correctly
function isConnected() {
if($this->conn)
return true;
return false;
}
// get a specific message (1 = first email, 2 = second email, etc.)
function getMessage($msg_index=NULL) {
if (!$this->isConnected || 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];
}
// return the messages in inbox folder
function getMessageNumber() {
if (!$this->isConnected) {
return;
}
return $this->msg_cnt;
}
// read all messages in the inbox folder
function inbox() {
if (!$this->conn) {
return;
}
$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;
}
}
// iniamos la clase
$mail=new Email_reader('servidor.com', '[email protected].com', 'xxxxxxxxxx');
if($mail->isConnected) {
echo "Error en la conexion";
return;
}
echo "Hay ".$mail->getMessageNumber()." mensajes en la bandeja de entrada";
// mostramos el contenido del primer mensaje
echo "<pre>";
print_r($mail->getMessage(1));
echo "</pre>";