Skip to content

Instantly share code, notes, and snippets.

@AlekVolsk
Last active August 20, 2022 21:13
Show Gist options
  • Save AlekVolsk/c0665e73face1bc68553257a2d4c7fca to your computer and use it in GitHub Desktop.
Save AlekVolsk/c0665e73face1bc68553257a2d4c7fca to your computer and use it in GitHub Desktop.
Скрипт уведомления о новых письмах в телеграм
<?php
/** @var string $timeZone */
$timeZone = 'Europe/Moscow';
/** @var bool $displayErrors */
$displayErrors = false;
/** @var array $mailConfig */
$mailConfig = [
'Yandex' => [
'address' => '{imap.yandex.ru:993/imap/ssl}',
'login' => 'my',
'password' => 'myapppassword',
'folders' => ['INBOX', 'Spam', 'Folder1', 'Folder1|Subfolder']
],
'Google' => [
'address' => '{imap.gmail.com:993/imap/ssl/novalidate-cert}',
'login' => 'my@gmail.com',
'password' => 'myapppassword',
'folders' => ['INBOX']
]
];
/** @var array $telegramConfig */
$telegramConfig = [
'token' => 'telegram bot token',
'chatId' => 'telegram chat ID'
];
<?php
/**
* check_utf8
*
* @param string $charset
* @return bool
*/
function check_utf8(string $charset): bool
{
return in_array(strtolower($charset), ['utf-8', 'default']);
}
/**
* convert_to_utf8
*
* @param string $in_charset
* @param string $str
* @return string
*/
function convert_to_utf8(string $in_charset, string $str): string
{
return (string)iconv(strtolower($in_charset), 'utf-8', $str);
}
/**
* get_imap_title
*
* @param string $str
* @return string
*/
function get_imap_title(string $str): string
{
$mime = imap_mime_header_decode($str);
$title = '';
foreach ($mime as $m) {
if (!check_utf8($m->charset)) {
$title .= convert_to_utf8($m->charset, $m->text);
} else {
$title .= $m->text;
}
}
return $title;
}
/**
* timezone_offset_string
*
* @return string
*/
function timezone_offset_string(): string
{
$offset = timezone_offset_get(new DateTimeZone(date_default_timezone_get()), new DateTime());
return sprintf('%s%02d%02d', ($offset >= 0) ? '+' : '-', abs($offset / 3600), abs($offset % 3600) / 60);
}
/**
* get_mails
*
* @param array $mailBoxes
* @param int $ts
* @param string $tzos
* @return array
*/
function get_mails(array $mailBoxes, int $ts, string $tzos = '+0000'): array
{
$mails = [];
$dt = date('d-M-Y H:i:00 ', $ts - (3600 * 6)) . $tzos;
foreach ($mailBoxes as $key => $mailBox) {
$folders = isset($mailBox['folders']) ? $mailBox['folders'] : ['INBOX'];
foreach ($folders as $folder) {
$mailKey = $key . ($folder == 'INBOX' ? '' : ' ' . $folder);
$imap = imap_open(
$mailBox['address'] . mb_convert_encoding($folder, 'UTF7-IMAP', 'UTF-8'),
$mailBox['login'],
$mailBox['password']
);
if ($imap !== false) {
$keys = imap_search($imap, 'SINCE "' . $dt . '"');
if ($keys) {
for ($i = (int)$keys[0]; $i <= (int)$keys[array_key_last($keys)]; $i++) {
$msgHeader = imap_headerinfo($imap, $i);
if ($msgHeader->udate > $ts) {
$mails[$mailKey][$i]['udate'] = $msgHeader->udate;
foreach ($msgHeader->from as $data) {
$mails[$mailKey][$i]['from'] = isset($data->personal)
? get_imap_title($data->personal) . ' (' . $data->mailbox . '@' . $data->host . ')'
: $data->mailbox . '@' . $data->host;
}
$mails[$mailKey][$i]['title'] = get_imap_title($msgHeader->subject);
}
}
}
imap_close($imap);
} else {
throw new Exception((string)imap_last_error());
}
}
}
return $mails;
}
/**
* file_get_contents_curl
*
* @param string $url
* @return string
*/
function file_get_contents_curl(string $url): string
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = (string)curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* seng_to_telegram
*
* @param array $config
* @param string $text
* @return array
*/
function seng_to_telegram(array $config, string $text): array
{
$urlSend = 'https://api.telegram.org/bot%s/sendMessage?'
. 'chat_id=%s&parse_mode=Markdown&text=%s&disable_web_page_preview=1';
$arr = explode('%0A', $text);
foreach ($arr as $k => $str) {
$arr[$k] = urlencode($str);
}
$text = str_replace('_', '\_', implode('%0A', $arr));
$result = json_decode(file_get_contents_curl(sprintf($urlSend, $config['token'], $config['chatId'], $text)), true);
return $result;
}
/**
* get_folders_list
*
* @param object $imap IMAP\Connection
* @param string $url
* @return array
*/
function get_folders_list(object $imap, string $url): array
{
$list = imap_list($imap, $url, '*') ?: [];
foreach ($list as $key => $folder) {
$list[$key] = mb_convert_encoding($folder, 'UTF-8', 'UTF7-IMAP');
}
return $list;
}
<?php
/**
* Скрипт уведомления о новых письмах в телеграм
* Работает через IMAP
* Для Яндекса и Google необходимо включить IMAP в настройках почтового ящика и создать пароль приложения
*/
include_once __DIR__ . '/config.php';
include_once __DIR__ . '/func.php';
date_default_timezone_set($timeZone);
ini_set('display_errors', $displayErrors ? '1' : '0');
error_reporting($displayErrors ? E_ALL : 0);
$ts = $ats = time();
if (file_exists(__DIR__ . '/ts.dat')) {
$ts = (int)file_get_contents(__DIR__ . '/ts.dat');
}
file_put_contents(__DIR__ . '/ts.dat', $ats);
$tzos = timezone_offset_string();
$mails = get_mails($mailConfig, $ts, $tzos);
if ($mails) {
foreach ($mails as $mailName => $mailBox) {
foreach ($mailBox as $mail) {
$text =
'*' . $mailName . '* | ' . date('H:i, d.m.Y', $mail['udate']) . '%0A' .
'`' . $mail['title'] . '`%0A' .
'`' . $mail['from'] . '`%0A';
seng_to_telegram($telegramConfig, $text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment