Código de PHP - Conectar a una cuenta de correo y descargar los mensajes de la bandeja de entrada

20120808
estrellaestrellaestrellaestrellaestrella(2)

Publicado el 5 de Febrero del 2019gráfica de visualizaciones de la versión: 20120808
5.073 visualizaciones desde el 5 de Febrero del 2019
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?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', 'usuario@dominio.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>";



Comentarios sobre la versión: 20120808 (2)

17 de Junio del 2019
estrellaestrellaestrellaestrellaestrella
No ha dejado ningún comentario
Responder
Imágen de perfil
6 de Marzo del 2022
estrellaestrellaestrellaestrellaestrella
Buenas tardes estimado, cree me pueda ayudar con este Codigo, me encuntro realizando un sistema de gestion de correo en PHP para mi intranet la cual me esta mostrando los correos por medio de imap_open() pero no logro que al pinchar en el Asunto o el Remitente este me abra en otra hoja el correo que he elegido, tampoco puedo hacer que la paguinacion funcione, me podria ayudar por favor, uso de base la Plantilla de AdminLTE
Saludos
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
<?php
  $page_title = 'Correo Electronico';
  require_once('includes/load.php');
?>
<?php
// Checkin What level user has permission to view this page
 page_require_level(4);
//pull out all informespreliminares form database
?>
<?php include_once('layouts/header.php'); ?>
 
<!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        Correo
        <!--<small>13 new messages</small>-->
      </h1>
      <ol class="breadcrumb">
        <li><a href="index.php"><i class="fa fa-dashboard"></i> Inicio</a></li>
        <li class="active">Correo</li>
      </ol>
    </section>
 
    <!-- Main content -->
    <section class="content">
         <div class="row">
        <div class="col-md-2">
          <a href="redactar_correo.php" class="btn btn-danger btn-block margin-bottom">Redactar Correo</a>
 
          <div class="box box-danger">
            <div class="box-header with-border">
              <h3 class="box-title">Carpetas</h3>
 
              <div class="box-tools">
                <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
                </button>
              </div>
            </div>
            <div class="box-body no-padding">
              <ul class="nav nav-pills nav-stacked">
                <li><a href="correo.php"><i class="fa fa-inbox"></i> Entrada
                  <span class="label label-primary pull-right"> 12</a></li>
                <li><a href="#"><i class="fa fa-envelope-o"></i> Enviados</a></li>
                <li><a href="#"><i class="fa fa-file-text-o"></i> Borradores</a></li>
                <li><a href="#"><i class="fa fa-filter"></i> Correo no deseado <span class="label label-warning pull-right">65</span></a>
                </li>
                <li><a href="#"><i class="fa fa-trash-o"></i> Papelera</a></li>
              </ul>
            </div>
            <!-- /.box-body -->
          </div>
          <!-- /. box -->
          <div class="box box-danger">
            <div class="box-header with-border">
              <h3 class="box-title">Etiquetas</h3>
 
              <div class="box-tools">
                <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
                </button>
              </div>
            </div>
            <!-- /.box-header -->
            <div class="box-body no-padding">
              <ul class="nav nav-pills nav-stacked">
                <li><a href="#"><i class="fa fa-circle-o text-red"></i> Importantes</a></li>
                <li><a href="#"><i class="fa fa-circle-o text-yellow"></i> Promociones</a></li>
                <li><a href="#"><i class="fa fa-circle-o text-light-blue"></i> Sociales</a></li>
              </ul>
            </div>
            <!-- /.box-body -->
          </div>
          <!-- /.box -->
        </div>
        <!-- /.col -->
         <div class="col-md-10">
          <div class="box box-danger">
            <div class="box-header with-border">
              <h3 class="box-title">Bandeja de Entrada</h3>
 
              <div class="box-tools pull-right">
                <div class="has-feedback">
                  <input type="text" class="form-control input-sm" placeholder="Buscar Correo">
                  <span class="glyphicon glyphicon-search form-control-feedback"></span>
                </div>
              </div>
              <!-- /.box-tools -->
            </div>
            <!-- /.box-header -->
            <div class="box-body no-padding">
              <div class="mailbox-controls">
                <!-- Check all button -->
                <button type="button" class="btn btn-default btn-sm checkbox-toggle"><i class="fa fa-square-o"></i>
                </button>
                <div class="btn-group">
                  <button type="button" class="btn btn-default btn-sm"><i class="fa fa-trash-o"></i></button>
                  <button type="button" class="btn btn-default btn-sm"><i class="fa fa-reply"></i></button>
                  <button type="button" class="btn btn-default btn-sm"><i class="fa fa-share"></i></button>
                </div>
                <!-- /.btn-group -->
                <button type="button" class="btn btn-default btn-sm"><i class="fa fa-refresh"></i></button>
                <div class="pull-right">
                  1-50/200
                  <div class="btn-group">
                    <button type="button" class="btn btn-default btn-sm"><i class="fa fa-chevron-left"></i></button>
                    <button type="button" class="btn btn-default btn-sm"><i class="fa fa-chevron-right"></i></button>
                  </div>
                  <!-- /.btn-group -->
                </div>
                <!-- /.pull-right -->
              </div>
              <div class="table-responsive mailbox-messages">
                <table class="table table-hover table-striped">
                  <tbody>
                    <?
 
$mailBoxes = array(
 
    array(
        'label'     => '<ANOTHER E-MAIL>',
        'enable'    => true,
        'mailbox'   => '{mail.domino.com:993/imap/ssl/novalidate-cert}INBOX',
        'username'  => $user['username'], //me toma los datos de la DB
        'password'  => $user['psw_mail'] //me toma los datos de la DB
    )
);
 
# Custom-fuctions
/**
 * Decode MIME message header extensions and get the text
 */
function decodeIMAPText( $str )
{
    $op = '';
    $decode_header = imap_mime_header_decode($str);
 
    foreach ($decode_header AS $obj)
    {
        $op .= htmlspecialchars(rtrim($obj->text, "\t"));
    }
 
    return $op;
}
?>
        <? if (!count($mailBoxes)) { ?>
 
            <p>::INVALID_CONFIG::</p>
 
        <? } else { ?>
 
            <?php foreach ($mailBoxes as $curMailBox) { ?>
 
                <h3><?php print $curMailBox['label']; ?></h3>
 
 
                    <?php
                    if (!$curMailBox['enable'])
                    {
                        print '<p>::DISABLED::</p>';
                    }
                    else
                    {
                        // IMAP Open
                        $inbox = @imap_open($curMailBox['mailbox'], $curMailBox['username'], $curMailBox['password']);
 
                        if ( $inbox )
                        {
                            // Get the last week's emails only
                            // Instead of searching for this week's message you could search for all the messages in your inbox using: $emails = imap_search($inbox,'ALL');
                            $emails = imap_search($inbox, 'SINCE '. date('d-M-Y',strtotime("-5 year")));
 
                            if (!count($emails))
                            {
                                print '<p>No E-mails found.</p>';
                            }
                            else
                            {
                                // Sort
                                rsort($emails);
 
                                foreach($emails as $email)
                                {
                                    // Fetch the email's overview and show subject, from and date.
                                    $overview = imap_fetch_overview($inbox,$email,0);
 
                                    // Message Body
                                    $message = imap_fetchbody($inbox,$email,'1.2');
                                    if ( trim($message) == '' )
                                    {
                                        $message = imap_fetchbody($inbox,$email,2);
                                    }
                                    $message = quoted_printable_decode($message);
 
                                    if ( trim($message) == '' )
                                    {
                                        $message = imap_fetchbody($inbox,$email,1);
                                    }
 
 
                                    ?>
                                            <tr>
                                              <td><input type="checkbox"></td>
                                              <td class="mailbox-star"><a href="#"><i class="fa fa-star text-yellow"></i></a></td>
                                              <td class="from" title="<?=decodeIMAPText($overview[0]->from)?>"><a href="leer_correo.php?id=<?=$overview[0]->id?>"><?=decodeIMAPText($overview[0]->from)?></a></td>
                                              <td class="subject" title="<?=decodeIMAPText($overview[0]->subject)?>"><b><?=decodeIMAPText($overview[0]->subject)?></b>
                                              </td>
                                              <td class="mailbox-attachment"></td>
                                              <td class="date"><?=$overview[0]->date?></td>
                                            </tr>
 
                                    <?php
                                }
                            }
 
                            imap_close($inbox);
                        }
                        else
                        {
                            print '<p>::CONNECTION_ERROR:: '. imap_last_error().'</p>';
                        }
                    }
                    ?>
 
 
            <?php } ?>
 
        <?php } ?>
 
                  </tbody>
                </table>
                <!-- /.table -->
              </div>
              <!-- /.mail-box-messages -->
            </div>
            <!-- /.box-body -->
            <div class="box-footer no-padding">
              <div class="mailbox-controls">
                <!-- Check all button -->
                <button type="button" class="btn btn-default btn-sm checkbox-toggle"><i class="fa fa-square-o"></i>
                </button>
                <div class="btn-group">
                  <button type="button" class="btn btn-default btn-sm"><i class="fa fa-trash-o"></i></button>
                  <button type="button" class="btn btn-default btn-sm"><i class="fa fa-reply"></i></button>
                  <button type="button" class="btn btn-default btn-sm"><i class="fa fa-share"></i></button>
                </div>
                <!-- /.btn-group -->
                <button type="button" class="btn btn-default btn-sm"><i class="fa fa-refresh"></i></button>
                <div class="pull-right">
                  1-50/200
                  <div class="btn-group">
                    <button type="button" class="btn btn-default btn-sm"><i class="fa fa-chevron-left"></i></button>
                    <button type="button" class="btn btn-default btn-sm"><i class="fa fa-chevron-right"></i></button>
                  </div>
                  <!-- /.btn-group -->
                </div>
                <!-- /.pull-right -->
              </div>
            </div>
          </div>
          <!-- /. box -->
        </div>
        <!-- /.col -->
      </div>
      <!-- /.row -->
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
 
  <?php include_once('layouts/footer.php'); ?>
Responder

Comentar la versión: 20120808

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s5055