Filter email by subject with PHP script

Asked

Viewed 388 times

0

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

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

I tried to adapt the script to read as I want, but it returns me 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 he returns this mistake:

Imagem de erro exibida no navegador pelo PHP

  • The function you are looking for is imap_search

  • I was able to open the emails the way I described, but I still get these error values (like in the image).

  • My suggestion was not to have to do the processing manually since the imap_search already brings an array of emails that have a certain criteria may be by title, size, date, etc. Regarding the error it seems to me that at least one of the emails did not get the Subject built. You are able to read some email at least, or error at all?

  • I can open all, the error was because some emails did not have Subject. Anyway, I was able to solve the problem, thank you very much!

1 answer

0


Try to use imap_fetch_overview()

i think this way is easier than using imap_header, 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
    }

}
  • I managed to solve my problem, thank you very much!

Browser other questions tagged

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