SHARE
TWEET

Get emails with PHP_imap

topherbones Jan 21st, 2020 (edited) 113 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. ########################################################################
  3. # Script has been altered by Chris Smith                               #
  4. # Base script courtesy of: https://app.getpocket.com/read/2180559750   #
  5. ########################################################################
  6.  
  7. //The location of the mailbox.
  8. $mailbox = '{localhost:143/notls}'; // (put /notls or /no-cert to disable that)
  9. //The username / email address that we want to login to.
  10. $username = 'youremailusername';
  11. //The password for this email address.
  12. $password = 'emailpassword';
  13.  
  14. //Attempt to connect using the imap_open function.
  15. $imapResource = imap_open($mailbox, $username, $password);
  16.  
  17. //If the imap_open function returns a boolean FALSE value,
  18. //then we failed to connect.
  19. if($imapResource === false){
  20.     //If it failed, throw an exception that contains
  21.     //the last imap error.
  22.     throw new Exception(imap_last_error());
  23. }
  24.  
  25. //If we get to this point, it means that we have successfully
  26. //connected to our mailbox via IMAP.
  27.  
  28. //Lets get all emails that were received since a given date.
  29. $search = 'SINCE "' . date("j F Y", strtotime("-7 days")) . '"';
  30. //Or comment out the above and uncomment below to get only unread
  31. // $search = imap_search($imapResource, 'UNSEEN');
  32. $emails = imap_search($imapResource, $search);
  33.  
  34.  
  35.  
  36.  
  37. //If the $emails variable is not a boolean FALSE value or
  38. //an empty array.
  39. if(!empty($emails)){
  40.     //Loop through the emails.
  41.     foreach($emails as $email){
  42.         //Fetch an overview of the email.
  43.         $overview = imap_fetch_overview($imapResource, $email);
  44.         $header = imap_headerinfo($imapResource, $email);
  45.         $overview = $overview[0];
  46.         //Print out the subject of the email.
  47.         echo '<b>' . htmlentities($overview->subject) . '</b><br>';
  48.         //Print out the sender's email address / from email address.
  49.         echo 'From: ' . $overview->from . '<br><br>';
  50.         $fromaddr = $header->from[0]->mailbox . "@" . $header->from[0]->host;
  51.         echo 'Email: ' . $fromaddr . '<br><br>';
  52.         //Get the body of the email.
  53.         $message = imap_fetchbody($imapResource, $email, 1, FT_PEEK);
  54.         echo $message;
  55.         echo "<p><hr></p>";
  56.     }
  57. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top