Просмотр файла system/libs/mail.class.php

Размер файла: 18.13Kb
  1. <?php
  2. class Mail
  3. {
  4. /* определение переменных идет через VAR, для обеспечения работы в php старых версий
  5. массивы адресов кому отправить
  6. @var array
  7. */
  8. var $sendto = array();
  9. /*
  10. @var array
  11. */
  12. var $acc = array();
  13. /*
  14. @var array
  15. */
  16. var $abcc = array();
  17. /*
  18. прикрепляемые файлы
  19. @var array
  20. */
  21. var $aattach = array();
  22. /*
  23. массив заголовков
  24. @var array
  25. */
  26. var $xheaders = array();
  27. /*
  28. приоритеты
  29. @var array
  30. */
  31. var $priorities = array( '1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)' );
  32. /*
  33. кодировка по умолчанию
  34. @var string
  35. */
  36. var $charset = "windows-1251";
  37. var $ctencoding = "8bit";
  38. var $receipt = 0;
  39. var $text_html="text/plain"; // формат письма. по умолчанию текстовый
  40. var $smtp_on=false; // отправка через smtp. по умолчанию выключена
  41. var $names_email = array(); // имена для email адресов, чтобы делать вид ("сергей" <asd@wer.re>)
  42.  
  43. /*
  44. конструктор тоже по старому объявлен для совместимости со старыми версиями php
  45. пошел конструктор.
  46. входящий параметр кодировка письма
  47. внесено изменение webi.ru
  48. */
  49.  
  50. function Mail($charset="")
  51. {
  52. $this->autoCheck( true );
  53. $this->boundary= "--" . md5( uniqid("myboundary") );
  54.  
  55.  
  56. if( $charset != "" ) {
  57. $this->charset = strtolower($charset);
  58. if( $this->charset == "us-ascii" )
  59. $this->ctencoding = "7bit";
  60. }
  61. }
  62.  
  63.  
  64. /*
  65.  
  66. включение выключение проверки валидности email
  67. пример: autoCheck( true ) проверка влючена
  68. по умолчанию проверка включена
  69.  
  70.  
  71. */
  72. function autoCheck( $bool )
  73. {
  74. if( $bool )
  75. $this->checkAddress = true;
  76. else
  77. $this->checkAddress = false;
  78. }
  79.  
  80.  
  81. /*
  82.  
  83. Тема письма
  84. внесено изменения кодирования не латинских символов
  85.  
  86. */
  87. function Subject( $subject )
  88. {
  89.  
  90. $this->xheaders['Subject'] ="=?".$this->charset."?Q?".str_replace("+","_",str_replace("%","=",urlencode(strtr( $subject, "\r\n" , " " ))))."?=";
  91.  
  92. }
  93.  
  94.  
  95. /*
  96.  
  97. от кого
  98. */
  99.  
  100. function From( $from )
  101. {
  102.  
  103. if( ! is_string($from) ) {
  104. echo "ошибка, From должен быть строкой";
  105. exit;
  106. }
  107. $temp_mass=explode(';',$from); // разбиваем по разделителю для выделения имени
  108. if(count($temp_mass)==2) // если удалось разбить на два элемента
  109. {
  110. $this->names_email['from']=$temp_mass[0]; // имя первая часть
  111. $this->xheaders['From'] = $temp_mass[1]; // адрес вторая часть
  112. }
  113. else // и если имя не определено
  114. {
  115. $this->names_email['from']='';
  116. $this->xheaders['From'] = $from;
  117. }
  118. }
  119.  
  120. /*
  121. на какой адрес отвечать
  122.  
  123. */
  124. function ReplyTo( $address )
  125. {
  126.  
  127. if( ! is_string($address) )
  128. return false;
  129.  
  130. $temp_mass=explode(';',$address); // разбиваем по разделителю для выделения имени
  131.  
  132. if(count($temp_mass)==2) // если удалось разбить на два элемента
  133. {
  134. $this->names_email['Reply-To']=$temp_mass[0]; // имя первая часть
  135. $this->xheaders['Reply-To'] = $temp_mass[1]; // адрес вторая часть
  136. }
  137. else // и если имя не определено
  138. {
  139. $this->names_email['Reply-To']='';
  140. $this->xheaders['Reply-To'] = $address;
  141. }
  142.  
  143.  
  144. }
  145.  
  146.  
  147. /*
  148. Добавление заголовка для получения уведомления о прочтении. обратный адрес берется из "From" (или из "ReplyTo" если указан)
  149.  
  150. */
  151.  
  152. function Receipt()
  153. {
  154. $this->receipt = 1;
  155. }
  156.  
  157.  
  158. /*
  159. set the mail recipient
  160. @param string $to email address, accept both a single address or an array of addresses
  161.  
  162. */
  163.  
  164. function To( $to )
  165. {
  166.  
  167. // если это массив
  168. if( is_array( $to ) )
  169. {
  170. foreach ($to as $key => $value) // перебираем массив и добавляем в массив для отправки через smtp
  171. {
  172.  
  173. $temp_mass=explode(';',$value); // разбиваем по разделителю для выделения имени
  174.  
  175. if(count($temp_mass)==2) // если удалось разбить на два элемента
  176. {
  177. $this->smtpsendto[$temp_mass[1]] = $temp_mass[1]; // ключи и значения одинаковые, чтобы исключить дубли адресов
  178. $this->names_email['To'][$temp_mass[1]]=$temp_mass[0]; // имя первая часть
  179. $this->sendto[]= $temp_mass[1];
  180. }
  181. else // и если имя не определено
  182. {
  183. $this->smtpsendto[$value] = $value; // ключи и значения одинаковые, чтобы исключить дубли адресов
  184. $this->names_email['To'][$value]=''; // имя первая часть
  185. $this->sendto[]= $value;
  186. }
  187. }
  188. }
  189. else
  190. {
  191. $temp_mass=explode(';',$to); // разбиваем по разделителю для выделения имени
  192.  
  193. if(count($temp_mass)==2) // если удалось разбить на два элемента
  194. {
  195. $this->sendto[] = $temp_mass[1];
  196. $this->smtpsendto[$temp_mass[1]] = $temp_mass[1]; // ключи и значения одинаковые, чтобы исключить дубли адресов
  197. $this->names_email['To'][$temp_mass[1]]=$temp_mass[0]; // имя первая часть
  198. }
  199. else // и если имя не определено
  200. {
  201. $this->sendto[] = $to;
  202. $this->smtpsendto[$to] = $to; // ключи и значения одинаковые, чтобы исключить дубли адресов
  203.  
  204. $this->names_email['To'][$to]=''; // имя первая часть
  205. }
  206. }
  207.  
  208. if( $this->checkAddress == true )
  209. $this->CheckAdresses( $this->sendto );
  210.  
  211. }
  212.  
  213.  
  214. /* Cc()
  215. * установка заголдовка CC ( открытая копия, все получатели будут видеть куда ушла копия )
  216. * $cc : email address(es), accept both array and string
  217. */
  218.  
  219. function Cc( $cc )
  220. {
  221. if( is_array($cc) )
  222. {
  223. $this->acc= $cc;
  224.  
  225. foreach ($cc as $key => $value) // перебираем массив и добавляем в массив для отправки через smtp
  226. {
  227. $this->smtpsendto[$value] = $value; // ключи и значения одинаковые, чтобы исключить дубли адресов
  228. }
  229. }
  230. else
  231. {
  232. $this->acc[]= $cc;
  233. $this->smtpsendto[$cc] = $cc; // ключи и значения одинаковые, чтобы исключить дубли адресов
  234. }
  235.  
  236. if( $this->checkAddress == true )
  237. $this->CheckAdresses( $this->acc );
  238.  
  239. }
  240.  
  241.  
  242.  
  243. /* Bcc()
  244. * скрытая копия. не будет помещать заголовок кому ушло письмо
  245. * $bcc : email address(es), accept both array and string
  246. */
  247.  
  248. function Bcc( $bcc )
  249. {
  250. if( is_array($bcc) )
  251. {
  252. $this->abcc = $bcc;
  253. foreach ($bcc as $key => $value) // перебираем массив и добавляем в массив для отправки через smtp
  254. {
  255. $this->smtpsendto[$value] = $value; // ключи и значения одинаковые, чтобы исключить дубли адресов
  256. }
  257. }
  258. else
  259. {
  260. $this->abcc[]= $bcc;
  261. $this->smtpsendto[$bcc] = $bcc; // ключи и значения одинаковые, чтобы исключить дубли адресов
  262. }
  263.  
  264. if( $this->checkAddress == true )
  265. $this->CheckAdresses( $this->abcc );
  266. }
  267.  
  268.  
  269. /* Body( text [ text_html ] )
  270. * $text_html в каком формате будет письмо, в тексте или html. по умолчанию стоит текст
  271. */
  272. function Body( $body, $text_html="" )
  273. {
  274. $this->body = $body;
  275.  
  276. if( $text_html == "html" ) $this->text_html = "text/html";
  277.  
  278. }
  279.  
  280.  
  281. /* Organization( $org )
  282. * set the Organization header
  283. */
  284.  
  285. function Organization( $org )
  286. {
  287. if( trim( $org != "" ) )
  288. $this->xheaders['Organization'] = $org;
  289. }
  290.  
  291.  
  292. /* Priority( $priority )
  293. * set the mail priority
  294. * $priority : integer taken between 1 (highest) and 5 ( lowest )
  295. * ex: $mail->Priority(1) ; => Highest
  296. */
  297.  
  298. function Priority( $priority )
  299. {
  300. if( ! intval( $priority ) )
  301. return false;
  302.  
  303. if( ! isset( $this->priorities[$priority-1]) )
  304. return false;
  305.  
  306. $this->xheaders["X-Priority"] = $this->priorities[$priority-1];
  307.  
  308. return true;
  309.  
  310. }
  311.  
  312.  
  313. /*
  314. прикрепленные файлы
  315.  
  316. @param string $filename : путь к файлу, который надо отправить
  317. @param string $webi_filename : реальное имя файла. если вдруг вставляется файл временный, то его имя будет хрен пойми каким..
  318. @param string $filetype : MIME-тип файла. по умолчанию 'application/x-unknown-content-type'
  319. @param string $disposition : инструкция почтовому клиенту как отображать прикрепленный файл ("inline") как часть письма или ("attachment") как прикрепленный файл
  320. */
  321.  
  322. function Attach( $filename, $webi_filename="", $filetype = "", $disposition = "inline" )
  323. {
  324. // TODO : если типа файла не указан, ставим неизвестный тип
  325. if( $filetype == "" )
  326. $filetype = "application/x-unknown-content-type";
  327.  
  328. $this->aattach[] = $filename;
  329. $this->webi_filename[] = $webi_filename;
  330. $this->actype[] = $filetype;
  331. $this->adispo[] = $disposition;
  332. }
  333.  
  334. /*
  335.  
  336. Собираем письмо
  337.  
  338.  
  339. */
  340. function BuildMail()
  341. {
  342.  
  343. $this->headers = "";
  344.  
  345. // создание заголовка TO.
  346. // добавление имен к адресам
  347. foreach ($this->sendto as $key => $value)
  348. {
  349. if( strlen($this->names_email['To'][$value])) $temp_mass[]="=?".$this->charset."?Q?".str_replace("+","_",str_replace("%","=",urlencode(strtr( $this->names_email['To'][$value], "\r\n" , " " ))))."?= <".$value.">";
  350. else $temp_mass[]=$value;
  351. }
  352. $this->xheaders['To'] = implode( ", ", $temp_mass ); // этот заголовок будет не нужен при отправке через mail()
  353.  
  354. if( count($this->acc) > 0 )
  355. $this->xheaders['CC'] = implode( ", ", $this->acc );
  356.  
  357. if( count($this->abcc) > 0 )
  358. $this->xheaders['BCC'] = implode( ", ", $this->abcc ); // этот заголовок будет не нужен при отправке через smtp
  359.  
  360.  
  361. if( $this->receipt ) {
  362. if( isset($this->xheaders["Reply-To"] ) )
  363. $this->xheaders["Disposition-Notification-To"] = $this->xheaders["Reply-To"];
  364. else
  365. $this->xheaders["Disposition-Notification-To"] = $this->xheaders['From'];
  366. }
  367.  
  368. if( $this->charset != "" ) {
  369. $this->xheaders["Mime-Version"] = "1.0";
  370. $this->xheaders["Content-Type"] = $this->text_html."; charset=$this->charset";
  371. $this->xheaders["Content-Transfer-Encoding"] = $this->ctencoding;
  372. }
  373.  
  374. $this->xheaders["X-Mailer"] = "PerfCMS Mailer";
  375.  
  376. // вставаляем файлы
  377. if( count( $this->aattach ) > 0 ) {
  378. $this->_build_attachement();
  379. } else {
  380. $this->fullBody = $this->body;
  381. }
  382.  
  383.  
  384.  
  385. // создание заголовков если отправка идет через smtp
  386. if($this->smtp_on)
  387. {
  388.  
  389. // разбиваем (FROM - от кого) на юзера и домен. домен понадобится в заголовке
  390. $user_domen=explode('@',$this->xheaders['From']);
  391.  
  392. $this->headers = "Date: ".date("D, j M Y G:i:s")." +0700\r\n";
  393. $this->headers .= "Message-ID: <".rand().".".date("YmjHis")."@".$user_domen[1].">\r\n";
  394.  
  395.  
  396. reset($this->xheaders);
  397. while( list( $hdr,$value ) = each( $this->xheaders ) ) {
  398. if( $hdr == "From" and strlen($this->names_email['from'])) $this->headers .= $hdr.": =?".$this->charset."?Q?".str_replace("+","_",str_replace("%","=",urlencode(strtr( $this->names_email['from'], "\r\n" , " " ))))."?= <".$value.">\r\n";
  399. elseif( $hdr == "Reply-To" and strlen($this->names_email['Reply-To'])) $this->headers .= $hdr.": =?".$this->charset."?Q?".str_replace("+","_",str_replace("%","=",urlencode(strtr( $this->names_email['Reply-To'], "\r\n" , " " ))))."?= <".$value.">\r\n";
  400. elseif( $hdr != "BCC") $this->headers .= $hdr.": ".$value."\r\n"; // пропускаем заголовок для отправки скрытой копии
  401.  
  402. }
  403.  
  404.  
  405.  
  406. }
  407. // создание заголовоков, если отправка идет через mail()
  408. else
  409. {
  410. reset($this->xheaders);
  411. while( list( $hdr,$value ) = each( $this->xheaders ) ) {
  412. if( $hdr == "From" and strlen($this->names_email['from'])) $this->headers .= $hdr.": =?".$this->charset."?Q?".str_replace("+","_",str_replace("%","=",urlencode(strtr( $this->names_email['from'], "\r\n" , " " ))))."?= <".$value.">\r\n";
  413. elseif( $hdr == "Reply-To" and strlen($this->names_email['Reply-To'])) $this->headers .= $hdr.": =?".$this->charset."?Q?".str_replace("+","_",str_replace("%","=",urlencode(strtr( $this->names_email['Reply-To'], "\r\n" , " " ))))."?= <".$value.">\r\n";
  414. elseif( $hdr != "Subject" and $hdr != "To") $this->headers .= "$hdr: $value\n"; // пропускаем заголовки кому и тему... они вставятся сами
  415. }
  416. }
  417.  
  418.  
  419.  
  420.  
  421. }
  422.  
  423. // включение отправки через smtp используя сокеты
  424. // после запуска этой функции отправка через smtp включена
  425. // для отправки через защищенное соединение сервер нужно указывать с добавлением "ssl://" например так "ssl://smtp.gmail.com"
  426. function smtp_on($smtp_serv, $login, $pass, $port=25,$timeout=5)
  427. {
  428. $this->smtp_on=true; // включаем отправку через smtp
  429.  
  430. $this->smtp_serv=$smtp_serv;
  431. $this->smtp_login=$login;
  432. $this->smtp_pass=$pass;
  433. $this->smtp_port=$port;
  434. $this->smtp_timeout=$timeout;
  435. }
  436.  
  437. function get_data($smtp_conn)
  438. {
  439. $data="";
  440. while($str = fgets($smtp_conn,515))
  441. {
  442. $data .= $str;
  443. if(substr($str,3,1) == " ") { break; }
  444. }
  445. return $data;
  446. }
  447.  
  448. /*
  449. отправка письма
  450.  
  451. */
  452. function Send()
  453. {
  454. $this->BuildMail();
  455. $this->strTo = implode( ", ", $this->sendto );
  456.  
  457. // если отправка без использования smtp
  458. if(!$this->smtp_on)
  459. {
  460. $res = @mail( $this->strTo, $this->xheaders['Subject'], $this->fullBody, $this->headers );
  461. }
  462. else // если через smtp
  463. {
  464.  
  465. if (!$this->smtp_serv OR !$this->smtp_login OR !$this->smtp_pass OR !$this->smtp_port) return false; // если нет хотя бы одного из основных данных для коннекта, выходим с ошибкой
  466.  
  467.  
  468.  
  469. // разбиваем (FROM - от кого) на юзера и домен. юзер понадобится в приветсвии с сервом
  470. $user_domen=explode('@',$this->xheaders['From']);
  471.  
  472.  
  473. $this->smtp_log='';
  474. $smtp_conn = fsockopen($this->smtp_serv, $this->smtp_port, $errno, $errstr, $this->smtp_timeout);
  475. if(!$smtp_conn) {$this->smtp_log .= "соединение с сервером не прошло\n\n"; fclose($smtp_conn); return; }
  476.  
  477. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  478.  
  479. fputs($smtp_conn,"EHLO ".$user_domen[0]."\r\n");
  480. $this->smtp_log .= "Я: EHLO ".$user_domen[0]."\n";
  481. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  482. $code = substr($data,0,3); // получаем код ответа
  483.  
  484. if($code != 250) {$this->smtp_log .= "ошибка приветсвия EHLO \n"; fclose($smtp_conn); return; }
  485.  
  486. fputs($smtp_conn,"AUTH LOGIN\r\n");
  487. $this->smtp_log .= "Я: AUTH LOGIN\n";
  488. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  489. $code = substr($data,0,3);
  490.  
  491. if($code != 334) {$this->smtp_log .= "сервер не разрешил начать авторизацию \n"; fclose($smtp_conn); return;}
  492.  
  493. fputs($smtp_conn,base64_encode($this->smtp_login)."\r\n");
  494. $this->smtp_log .= "Я: ".base64_encode($this->smtp_login)."\n";
  495. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  496.  
  497. $code = substr($data,0,3);
  498. if($code != 334) {$this->smtp_log .= "ошибка доступа к такому юзеру\n"; fclose($smtp_conn); return ;}
  499.  
  500.  
  501. fputs($smtp_conn,base64_encode($this->smtp_pass)."\r\n");
  502. $this->smtp_log .="Я: ". base64_encode($this->smtp_pass)."\n";
  503. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  504.  
  505. $code = substr($data,0,3);
  506. if($code != 235) {$this->smtp_log .= "не правильный пароль\n"; fclose($smtp_conn); return ;}
  507.  
  508. fputs($smtp_conn,"MAIL FROM:<".$this->xheaders['From']."> SIZE=".strlen($this->headers."\r\n".$this->fullBody)."\r\n");
  509. $this->smtp_log .= "Я: MAIL FROM:<".$this->xheaders['From']."> SIZE=".strlen($this->headers."\r\n".$this->fullBody)."\n";
  510. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  511.  
  512. $code = substr($data,0,3);
  513. if($code != 250) {$this->smtp_log .= "сервер отказал в команде MAIL FROM\n"; fclose($smtp_conn); return ;}
  514.  
  515.  
  516.  
  517. foreach ($this->smtpsendto as $keywebi => $valuewebi)
  518. {
  519. fputs($smtp_conn,"RCPT TO:<".$valuewebi.">\r\n");
  520. $this->smtp_log .= "Я: RCPT TO:<".$valuewebi.">\n";
  521. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  522. $code = substr($data,0,3);
  523. if($code != 250 AND $code != 251) {$this->smtp_log .= "Сервер не принял команду RCPT TO\n"; fclose($smtp_conn); return ;}
  524. }
  525.  
  526.  
  527.  
  528.  
  529. fputs($smtp_conn,"DATA\r\n");
  530. $this->smtp_log .="Я: DATA\n";
  531. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  532.  
  533. $code = substr($data,0,3);
  534. if($code != 354) {$this->smtp_log .= "сервер не принял DATA\n"; fclose($smtp_conn); return ;}
  535.  
  536. fputs($smtp_conn,$this->headers."\r\n".$this->fullBody."\r\n.\r\n");
  537. $this->smtp_log .= "Я: ".$this->headers."\r\n".$this->fullBody."\r\n.\r\n";
  538.  
  539. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  540.  
  541. $code = substr($data,0,3);
  542. if($code != 250) {$this->smtp_log .= "ошибка отправки письма\n"; fclose($smtp_conn); return ;}
  543.  
  544. fputs($smtp_conn,"QUIT\r\n");
  545. $this->smtp_log .="QUIT\r\n";
  546. $this->smtp_log .= $data = $this->get_data($smtp_conn)."\n";
  547. fclose($smtp_conn);
  548. }
  549.  
  550. }
  551.  
  552.  
  553.  
  554. /*
  555. * показывает что было отправлено
  556. *
  557. */
  558.  
  559. function Get()
  560. {
  561. if(isset($this->smtp_log))
  562. {
  563. if ($this->smtp_log)
  564. {
  565. return $this->smtp_log; // если есть лог отправки smtp выведем его
  566. }
  567. }
  568.  
  569. $this->BuildMail();
  570. $mail = $this->headers . "\n\n";
  571. $mail .= $this->fullBody;
  572. return $mail;
  573. }
  574.  
  575.  
  576. /*
  577. проверка мыла
  578. возвращает true или false
  579. */
  580.  
  581. function ValidEmail($address)
  582. {
  583.  
  584. // если существует современная функция фильтрации данных, то проверять будем этой функцией. появилась в php 5.2
  585. if (function_exists('filter_list'))
  586. {
  587. $valid_email = filter_var($address, FILTER_VALIDATE_EMAIL);
  588. if ($valid_email !== false) return true;
  589. else return false;
  590. }
  591. else // а если php еще старой версии, то проверка валидности пойдет старым способом
  592. {
  593. if( ereg( ".*<(.+)>", $address, $regs ) ) {
  594. $address = $regs[1];
  595. }
  596. if(ereg( "^[^@ ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|net|com|gov|mil|org|edu|int)\$",$address) )
  597. return true;
  598. else
  599. return false;
  600. }
  601. }
  602.  
  603.  
  604. /*
  605.  
  606. проверка массива адресов
  607.  
  608.  
  609. */
  610.  
  611. function CheckAdresses( $aad )
  612. {
  613. for($i=0;$i< count( $aad); $i++ ) {
  614. if( ! $this->ValidEmail( $aad[$i]) ) {
  615. echo "ошибка : не верный email ".$aad[$i];
  616. exit;
  617. }
  618. }
  619. }
  620.  
  621.  
  622. /*
  623. сборка файлов для отправки
  624. */
  625.  
  626. function _build_attachement()
  627. {
  628.  
  629. $this->xheaders["Content-Type"] = "multipart/mixed;\n boundary=\"$this->boundary\"";
  630.  
  631. $this->fullBody = "This is a multi-part message in MIME format.\n--$this->boundary\n";
  632. $this->fullBody .= "Content-Type: ".$this->text_html."; charset=$this->charset\nContent-Transfer-Encoding: $this->ctencoding\n\n" . $this->body ."\n";
  633.  
  634. $sep= chr(13) . chr(10);
  635.  
  636. $ata= array();
  637. $k=0;
  638.  
  639. // перебираем файлы
  640. for( $i=0; $i < count( $this->aattach); $i++ ) {
  641.  
  642. $filename = $this->aattach[$i];
  643.  
  644. $webi_filename =$this->webi_filename[$i]; // имя файла, которое может приходить в класс, и имеет другое имя файла
  645. if(strlen($webi_filename)) $basename=basename($webi_filename); // если есть другое имя файла, то оно будет таким
  646. else $basename = basename($filename); // а если нет другого имени файла, то имя будет выдернуто из самого загружаемого файла
  647.  
  648. $ctype = $this->actype[$i]; // content-type
  649. $disposition = $this->adispo[$i];
  650.  
  651. if( ! file_exists( $filename) ) {
  652. echo "ошибка прикрепления файла : файл $filename не существует"; exit;
  653. }
  654. $subhdr= "--$this->boundary\nContent-type: $ctype;\n name=\"$basename\"\nContent-Transfer-Encoding: base64\nContent-Disposition: $disposition;\n filename=\"$basename\"\n";
  655. $ata[$k++] = $subhdr;
  656. // non encoded line length
  657. $linesz= filesize( $filename)+1;
  658. $fp= fopen( $filename, 'r' );
  659. $ata[$k++] = chunk_split(base64_encode(fread( $fp, $linesz)));
  660. fclose($fp);
  661. }
  662. $this->fullBody .= implode($sep, $ata);
  663. }
  664.  
  665.  
  666. }