Skip to content

Instantly share code, notes, and snippets.

@tommyready
Last active June 18, 2018 18:23
Show Gist options
  • Save tommyready/c15463a6a2ed9a7267849e96409ad9fa to your computer and use it in GitHub Desktop.
Save tommyready/c15463a6a2ed9a7267849e96409ad9fa to your computer and use it in GitHub Desktop.
Laravel IMAP Service
<?php
namespace App\Services;
class ImapService {
protected $imapHost;
protected $imapEmail;
protected $imapPassword;
protected $searchCriteria;
protected $seen;
protected $removeTags;
protected $inbox;
protected $emailData;
protected $emails = [];
public function __construct($imap_host,$imap_email,$imap_password,$subject,$seen=false,$removeTags=true) {
$this->imapHost = $imap_host;
$this->imapEmail = $imap_email;
$this->imapPassword = $imap_password;
$this->seen = $seen;
$this->removeTags = $removeTags;
$this->searhCriteria = $this->_buildSearchCriteria($subject);
return $this;
}
public function getEmails() {
try {
$this->_openInbox();
$this->_searchInbox();
$this->_parseEmails();
} catch( Exception $e ) {
\Log::Error(imap_last_error());
}
return $this->emails;
}
private function _buildSearchCriteria($subject) {
return sprintf('FROM "%s" SUBJECT "%s" %s',$this->imapEmail,$subject,$this->_isSeen());
}
private function _isSeen() {
return ($this->seen ? 'SEEN' : 'UNSEEN');
}
private function _openInbox() {
$this->inbox = imap_open($this->imapHost, $this->imapEmail, $this->imapPassword);
}
private function _searchInbox() {
$this->emailData = imap_search($this->inbox, $this->searhCriteria);
}
private function _parseEmails() {
if($this->emailData) {
foreach ($this->emailData as $emailNumber){
array_push($this->emails,$this->_getEmail($emailNumber));
}
}
}
private function _getEmail($emailNumber) {
$message = imap_fetchbody ($this->inbox, $emailNumber, 2);
if($this->removeTags) return trim(preg_replace('/\s+/', ' ', strip_tags( $message )));
return $message;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment