IMAP access to google is open for all. I assumed that you already know what is IMAP and Google Settings. So, you can grab my written here. For a generic IMAP connection to google mail, you need to set SSL no-validate option as well.
$inbox = @imap_open("{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX", $email, $password);
Port 993 is for gmail secured IMAP. And 995 is for POP3. We can use POP3 protocol instead of IMAP here –
$inbox = @imap_open("{pop.gmail.com:995/pop3/ssl/novalidate-cert}INBOX", $email, $password);
“ssl” will transport the data using “tsl” protocol for mail. “novalidate-cert” will not try to validate the SSL certificate from the user side. It is mandatory to access secured server if we have not .cert file to validate connection. Here “INBOX” is the mailbox which we want to access for mails, we can change it for our needs, such as it might be “Trash”.
if(!$inbox) die("Mail server connect failed"); $foo = imap_errors();
After successful login to IMAP server, we want to count the total mail. So –
$total = imap_num_msg($inbox); if($total < 1) { echo "No Message for $email"; } else { echo "Our code goes here in the next";} [/php] Now we will access the email from the mailbox - [php] for ( $i=$total; $i >= 1; $i-- ) { $headers = @imap_header($inbox, $i); $fromaddress = $headers->from[0]->mailbox . '@' . $headers->from[0]->host; echo $message_body = @imap_body( $inbox, $i); }
If we want to delete this mail from inbox, then we need to call imap_delete() function. And to move the mail to trash, we need to call imap_mail_move() function with mailbox name ‘[Gmail]/Trash’ parameter.
@imap_delete($inbox, $i); @imap_mail_move($inbox, "$i:$i", '[Gmail]/Trash');
To close the mailbox, we need to call imap_close() function. And calling of imap_expunge() function is mandatory to delete the mails which are marked from the code above. imap_expunge() should call before imap_close() function.
@imap_expunge($inbox); @imap_close($inbox);
Complete code:
$inbox = @imap_open("{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX", $email, $password); if(!$inbox) die("Mail server connect failed"); $foo = imap_errors(); $total = imap_num_msg($inbox); if($total < 1) { echo "No Message for $email"; } else { for ( $i=$total; $i >= 1; $i-- ) { $headers = @imap_header($inbox, $i); $fromaddress = $headers->from[0]->mailbox . '@' . $headers->from[0]->host; echo $message_body = @imap_body( $inbox, $i); if($headers->fromaddress == '[email protected]') { @imap_delete($inbox, $i); @imap_mail_move($inbox, "$i:$i", '[Gmail]/Trash'); } } } @imap_expunge($inbox); @imap_close($inbox); ?>