Advertisement
topherbones

Get emails with PHP_imap

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