|
|
|
| Добрый день,
у меня есть скрипт, который проверяет почту с определенной периодичностью и, если есть новая почта, скидывает мне SMS-кой, выглядит это примерно так:
$mbox = imap_open("{".$email_server.":110/pop3}INBOX", $email_account, $email_password) or die("Error at line 20");
$mcheck = imap_check($mbox);
$mcount = $mcheck->Nmsgs;
if ($mcount>0) {
for($i=1; $i<=$mcount; $i++) {
$overview = imap_fetch_overview($mbox, "1:$i", 0);
// get message data fields
$msg_from = eregi_replace(".*<([_a-z0-9-]+@[a-z0-9-]+.[a-z0-9-]+)>.*", "\\1", $overview[0]->from);
$msg_date = eregi_replace(".*, ([0-9]+)[ a-z]+[0-9]{2}([0-9]+).+([0-9]+):([0-9]+):([0-9]+).*", "\\1.\\2 \\3:\\4", $overview[0]->date);
$msg_body = imap_fetchbody($mbox, $i, 1);
// Возможно здесь потребуется перекодировать сообщение, или даже поделить его на части, потом доделаю
if(is_new_message($msg_from, $msg_date)) {
send_sms_notify($msg_from, $msg_date, $msg_body);
add_to_base($msg_from, $msg_date);
}
}
}
imap_close($mbox);
|
Только частенько приходят SMS-ки вида:
=C7=E4=F0=E0=E2 и т.д.
или
=?koi8-r?B?98/My8/XIOHOxNLFyiD3 и т.д.
Я все равно перекодирую потом текст в транслит, поэтому мне подскажите пожалуйста, еслть ли какой-нибудь универсальный способ раскодировать и koi8 и base64 (я предполагаю первая SMS-ка закодированна им).
Возможно есть какие-то функции в imap_* | |
|
|
|
|
|
|
|
для: Wyfinger
(04.06.2009 в 01:43)
| | Задачу решил сам, если кому еще будет интересно привожу код решения:
if ($mcount>0) {
for($i=1; $i<=$mcount; $i++) {
$overview = imap_fetch_overview($mbox, "1:$i", 0);
// get message data fields
$msg_from = eregi_replace(".*<([_a-z0-9-]+@[a-z0-9-]+.[a-z0-9-]+)>.*", "\\1", $overview[0]->from);
$msg_date = eregi_replace(".*, ([0-9]+)[ a-z]+[0-9]{2}([0-9]+).+([0-9]+):([0-9]+):([0-9]+).*", "\\1.\\2 \\3:\\4", $overview[0]->date);
$msg_body = imap_fetchbody($mbox, $i, 1);
// detect excode character
$imhd = imap_mime_header_decode($overview[0]->from);
if($imhd[0]->charset == 'koi8-r') $ch_from = 'k';
if($imhd[0]->charset == 'iso8859-5') $ch_from = 'i';
if($imhd[0]->charset == 'x-cp866') $ch_from = 'a';
if($imhd[0]->charset == 'x-mac-cyrillic') $ch_from = 'm';
if(isset($ch_from)) $msg_body = convert_cyr_string($msg_body, $ch_from, 'w');
// convert mime and concatenate
$msg_body = imTranslite(imap_qprint($msg_body));
// check and send sms
if(is_new_message($msg_from, $msg_date)) {
send_sms_notify($msg_from, $msg_date, $msg_body);
add_to_base($msg_from, $msg_date);
}
}
}
|
| |
|
|
|
|
|
|
|
для: Wyfinger
(04.06.2009 в 01:43)
| | Предыдущий вариант не совсем правильно работал, я получал кодировку из поля from, но оно может быть заполненно только английскими, тогда кодировка будет default, а текст письма может быть при этом в koi8-r. Исправил, кодировка теперь кодировка извлекается из поля Content-Type, charset, хеадера письма.
Я подумал, скрипт простой, но весьма полезный, поэтому выкладываю для всеобщего пользования. Для настройки нужно указать сервер, постовый ящик, пароль, номер телефона и sms-гейт своего оператора.
<?php
// ******************************************************
// SMS EMail Notifer
// this script will notify you about new email by sms
// we works with POP3 protocol
//
// Copyright (C) 2009, Wyfinger
// ******************************************************
// Configuration
$email_server = "pop.mail.ru"; // pop server
$email_account = "_your_mail_@mail.ru"; // e-mail
$email_password = "_your_password_"; // password
$sms_gate = "@sms.mtsdv.ru"; // SMS gate, find for Your operator
$sms_telephone = "_your_tel_"; // telephone
$index_base = "smsemail.dat";
// if this is a new message, this function will return true
function is_new_message($from, $date) {
$result = true;
$index_base = $GLOBALS["index_base"];
$index = substr(md5($from.$date),1, 10);
if ($fp = fopen($index_base, 'r')) {
$base = fread($fp, filesize($index_base));
if(strstr($base, $index)) {
$result = false;
}
fclose($fp);
}
return $result;
}
// this function save message hash to base
function add_to_base($from, $date) {
$result = false;
$index_base = $GLOBALS["index_base"];
$index = substr(md5($from.$date),1, 10);
if ($fp = fopen($index_base, 'a+')) {
fseek($fp, 0);
$base = fread($fp, filesize($index_base));
$base = $index."\n";
fwrite($fp, $base);
fclose($fp);
}
return $result;
}
// transliterate text
function imTranslite($str) {
static $tbl= array(
'а'=>'a', 'б'=>'b', 'в'=>'v', 'г'=>'g', 'д'=>'d', 'е'=>'e', 'ж'=>'g', 'з'=>'z',
'и'=>'i', 'й'=>'y', 'к'=>'k', 'л'=>'l', 'м'=>'m', 'н'=>'n', 'о'=>'o', 'п'=>'p',
'р'=>'r', 'с'=>'s', 'т'=>'t', 'у'=>'u', 'ф'=>'f', 'ы'=>'i', 'э'=>'e', 'А'=>'A',
'Б'=>'B', 'В'=>'V', 'Г'=>'G', 'Д'=>'D', 'Е'=>'E', 'Ж'=>'G', 'З'=>'Z', 'И'=>'I',
'Й'=>'Y', 'К'=>'K', 'Л'=>'L', 'М'=>'M', 'Н'=>'N', 'О'=>'O', 'П'=>'P', 'Р'=>'R',
'С'=>'S', 'Т'=>'T', 'У'=>'U', 'Ф'=>'F', 'Ы'=>'I', 'Э'=>'E', 'ё'=>"yo", 'х'=>"h",
'ц'=>"ts", 'ч'=>"ch", 'ш'=>"sh", 'щ'=>"shch", 'ъ'=>"", 'ь'=>"", 'ю'=>"yu", 'я'=>"ya",
'Ё'=>"YO", 'Х'=>"H", 'Ц'=>"TS", 'Ч'=>"CH", 'Ш'=>"SH", 'Щ'=>"SHCH", 'Ъ'=>"", 'Ь'=>"",
'Ю'=>"YU", 'Я'=>"YA"
);
return strtr($str, $tbl);
}
// this function send sms
function send_sms_notify($from, $date, $body) {
$message = $body;
$search = array(" ", "..", ",,", "--", "!!", "??", "\n\n");
$replace = array(" ", ".", ",", "-", "!", "?", "\n");
// delete dublesighs and trim
$message = trim(str_replace($search, $replace, $message));
$message = $from."\n".$message;
$msg_len = strlen($message);
if($msg_len>110) {
$msg1 = trim(substr($message, 0, 110));
$msg2 = trim(substr($message, 110, 110));
$msg3 = trim(substr($message, 220, 110));
} else {
$msg1 = $message;
}
if($msg1!="") mail($GLOBALS["sms_telephone"].$GLOBALS["sms_gate"], "", $msg1);
sleep(5);
if($msg2!="") mail($GLOBALS["sms_telephone"].$GLOBALS["sms_gate"], "", $msg2);
sleep(5);
if($msg3!="") mail($GLOBALS["sms_telephone"].$GLOBALS["sms_gate"], "", $msg3);
print "<b>Send:</b><br>$from<br>$date<br>$body<hr><br>";
}
// ******************************************************
$mbox = imap_open("{".$email_server.":110/pop3}INBOX", $email_account, $email_password) or die("Error at line 20");
$mcheck = imap_check($mbox);
$mcount = $mcheck->Nmsgs;
if ($mcount>0) {
for($i=1; $i<=$mcount; $i++) {
$overview = imap_fetch_overview($mbox, "1:$i", 0);
$header = imap_fetchheader($mbox, "1:$i");
// get message data fields
$msg_from = eregi_replace(".*<([_a-z0-9-]+@[a-z0-9-]+.[a-z0-9-]+)>.*", "\\1", $overview[0]->from);
$msg_date = eregi_replace(".*, ([0-9]+)[ a-z]+[0-9]{2}([0-9]+).+([0-9]+):([0-9]+):([0-9]+).*", "\\1.\\2 \\3:\\4", $overview[0]->date);
$msg_body = imap_fetchbody($mbox, $i, 1);
// detect excode character from mail header
$charset = preg_replace('/.*charset=([\w\-]+).*/s', '$1', $header);
if($charset == 'koi8-r') $ch_from = 'k';
if($charset == 'iso8859-5') $ch_from = 'i';
if($charset == 'x-cp866') $ch_from = 'a';
if($charset == 'x-mac-cyrillic') $ch_from = 'm';
if(isset($ch_from)) $msg_body = convert_cyr_string($msg_body, $ch_from, 'w');
// convert mime and concatenate
$msg_body = imTranslite(imap_qprint($msg_body));
// check and send sms
if(is_new_message($msg_from, $msg_date)) {
send_sms_notify($msg_from, $msg_date, $msg_body);
add_to_base($msg_from, $msg_date);
}
}
}
imap_close($mbox);
print '<strong>Ok</strong>';
?>
|
Скрипт сохраняет базу сообщений (хеши) в файл, БД не используется.
Скрипт можно поставить в cron, а если Ваш хостинг план его не поддерживает, можно воспользоваться сервисом [url]www.mywebcron.com[/url], я поставил себе на выполнение раз в минуту. | |
|
|
|
|