Skip to content

Instantly share code, notes, and snippets.

@Goerik
Created October 28, 2016 08:46
Show Gist options
  • Save Goerik/555ba6178156d61b78492080a0d31c93 to your computer and use it in GitHub Desktop.
Save Goerik/555ba6178156d61b78492080a0d31c93 to your computer and use it in GitHub Desktop.
/**
* "require": {
* "php": ">=5.4",
"php-imap/php-imap": "~2.0",
"phpmailer/phpmailer": "^5.2"
* },
*
* sudo apt-get install php-imap
*
*/
use PhpImap\IncomingMail;
class MailService
{
private
$mailbox;
public function __construct()
{
$this->username = 'email@gmail.com';
$this->password = 'password';
$this->mailbox = new PhpImap\Mailbox('{imap.gmail.com:993/imap/ssl}INBOX', $this->username, $this->password, __DIR__);
}
/**
* Подготавливает мейлер для отправки
* @return PHPMailer
*/
protected function getOutgoingMailer()
{
$mailer = new PHPMailer;
$mailer->isSMTP();
$mailer->Host = 'smtp.gmail.com';
$mailer->SMTPAuth = true;
$mailer->Username = $this->username;
$mailer->Password = $this->password;
$mailer->SMTPSecure = 'tls';
$mailer->Port = 587;
$mailer->setFrom($this->username, 'Mail Bot');
$mailer->isHTML(false);
return $mailer;
}
/**
* Отправляет письмо с вложениями
* @param $to
* @param $subject
* @param $body
* @param array $files
* @return bool
*/
public function sendMail($to, $subject, $body, array $files = [])
{
$mailer = $this->getOutgoingMailer();
$mailer->addAddress($to);
foreach ($files as $file)
{
$mailer->addAttachment($file);
}
$preferences = array(
"input-charset" => "UTF-8",
"output-charset" => "UTF-8",
"line-length" => 76,
"line-break-chars" => "\n",
"scheme" => "Q"
);
$mailer->Subject = iconv_mime_encode("Subject", $subject, $preferences);
$mailer->Body = $body;
return $mailer->send();
}
/**
* Возвращает поисковый критерий для поиска по email
* @param $email
* @return string
*/
public function getCriteria($email)
{
return 'UNSEEN from "' . $email . '"';
}
/**
* Возвраащет поисковый критерий для поиска всех непрочитанных сообщений
* @return string
*/
public function getCriteriaAllUnseen()
{
return 'UNSEEN';
}
/**
* Возвращает последнее непрочитанное сообщение от пользователя с $email
* @param $email
* @return null|IncomingMail
*/
public function getLastUnreadMessage($email)
{
$mailsIds = $this->mailbox->searchMailbox($this->getCriteria($email));
$msgId = end($mailsIds);
if ($msgId !== false)
{
return $this->mailbox->getMail($msgId, false);
}
return null;
}
/**
* Помечает все непрочитанные сообщения прочитанными
*/
public function markAllMessagesAsSeen()
{
$mailsIds = $this->mailbox->searchMailbox($this->getCriteriaAllUnseen());
foreach ($mailsIds as $mailsId)
{
$this->mailbox->markMailAsRead($mailsId);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment