topherbones icon

Get emails with PHP_imap

topherbones | PRO | 12/02/20 11:40:24 PM UTC (Edited) | 0 ⭐ | 828 👁️ | Never ⏰ | []
PHP |

2.17 KB

|

None

|

0 👍

/

0 👎

<?php
########################################################################
# Script has been altered by Chris Smith                               #
# Base script courtesy of: https://app.getpocket.com/read/2180559750   #
########################################################################
//The location of the mailbox.
$mailbox = "{mail.domain.com:993/imap/ssl/novalidate-cert}INBOX"; // (put /notls or /no-cert to disable that)
//The username / email address that we want to login to.
$username = 'emailAddress';
//The password for this email address.
$password = 'emailPassword';
 
//Attempt to connect using the imap_open function.
$imapResource = imap_open($mailbox, $username, $password);
 
//If the imap_open function returns a boolean FALSE value,
//then we failed to connect.
if($imapResource === false){
    //If it failed, throw an exception that contains
    //the last imap error.
    throw new Exception(imap_last_error());
}
 
//If we get to this point, it means that we have successfully
//connected to our mailbox via IMAP.
 
//Lets get all emails that were received since a given date.
//$search = 'SINCE "' . date("j F Y", strtotime("-7 days")) . '"';
//Or comment out the above and uncomment below to get only unread
$emails = imap_search($imapResource, 'UNSEEN');
 
 
//If the $emails variable is not a boolean FALSE value or
//an empty array.
if(!empty($emails)){
    //Loop through the emails.
    foreach($emails as $email){
        //Fetch an overview of the email.
        $overview = imap_fetch_overview($imapResource, $email);
        $header = imap_headerinfo($imapResource, $email);
        $overview = $overview[0];
        //Print out the subject of the email.
        echo '<b>' . iconv_mime_decode($overview->subject,0,"ISO-8859-1") . '</b><br>';
        //Print out the sender's email address / from email address.
        echo 'From: ' . imap_utf8($overview->from)  . '<br><br>';
        $fromaddr = $header->from[0]->mailbox . "@" . $header->from[0]->host;
        echo 'Email: ' . $fromaddr . '<br><br>';
        //Get the body of the email.
        $message = imap_fetchbody($imapResource, $email, 1, FT_PEEK);
        echo $message;
        echo "<p><hr></p>";
    }
}
 
?>

Comments