Filter email by subject with PHP script

0

Well, I have a script that reads the email, however I have to pass as the parameter the sequence number of the message I want to open.

I would like to open the messages with a given Subject and perform operations with them.

I tried to adapt the script to read as I want, but it returns me an error.

    $login = 'email';
    $senha = 'senha';

    $str_conexao = '{imap.gmail.com:993/imap/ssl}';
    if (!extension_loaded('imap')) {
        die('Modulo PHP/IMAP nao foi carregado');
     }

     // Abrindo conexao
    $mailbox = imap_open($str_conexao, $login, $senha);
    if (!$mailbox) {
       die('Erro ao conectar: '.imap_last_error());
     } 
    $check = imap_check($mailbox);

    // Ultima mensagem
    echo "Data ".$check->Date."<br>";

    // Tipo de conexao
    echo "Conexão ".$check->Driver."<br>";

    // Mailbox
    echo "Caixa de email ".$check->Mailbox."<br>";

    // Numero de mensagens total
    echo "Mensagens total ".$check->Nmsgs."<br>";

   //ultima mensagem recebida
   $msg = $check->Nmsgs;

   $i=1;
while ( $i < $msg ) {

$header = imap_header($mailbox, $i);

$subject_hold = $header->Subject;
if($subject_hold == "TESTE"){
    echo "Resultado encontrado: <br>";
    /*
    // Data
    echo $header->Date;
    // Endereco do destinatario
    echo $header->toaddress;
    // Endereco do remetente
    echo $header->fromaddress;
    */
    // Assunto da mensagem
    echo $header->Subject."<br>";
    }
  $i++;
}

But it returns me this error:

    
asked by anonymous 05.08.2017 / 17:08

1 answer

0

Try using imap_fetch_overview ()

I think this is easier than using imap_header, for example:

// usei o ciclo for porque é mais conveniente nesta situação
// tem cuidado com $i = 1, verifica se começa no indice 0
for ($i = 1; $i < $check->Nmsgs; $i++) { 

    $overview = imap_fetch_overview($mailbox, $i, 0);

    if($overview[0]->subject == "TESTE")
    {
        // teu codigo
    }

}
    
05.08.2017 / 19:05