Отправка почты (Класс)
- class KMail {
- private $mb = false;
- private $header = false;
- private $subject = '(No subject)';
- private $to = array();
- private $body = '';
- public function __construct() {
- $this->set_mb();
- }
- public function send_mail_utf8($to, $subject, $message, $header) {
- return mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $message, 'MIME-Version: 1.0' . PHP_EOL . $header);
- }
- public function send() {
- if (!$this->get_mb()) {
- throw new Exception('Ошибка установки уникального значения');
- }
- if (!$this->get_header()) {
- $this->set_header();
- }
- if (!$this->get_body()) {
- throw new Exception('Отсутсвует тело письма');
- }
- if (sizeof($this->to) > 0) {
- foreach($this->to as $to) {
- $this->send_mail_utf8($to, $this->get_subject(), $this->get_body() . $this->end_body(), $this->get_header());
- }
- } else {
- throw new Exception('Отсутствует адресат');
- }
- }
- public function add_to($mail) {
- $this->to[] = $mail;
- }
- public function add_body_message($text) {
- $this->body .= '--' . $this->mb . PHP_EOL .
- 'Content-Type: text/plain; charset="UTF-8"' . PHP_EOL .
- 'Content-Disposition: inline' . PHP_EOL .
- 'Content-Transfer-Encoding: base64' . PHP_EOL . PHP_EOL .
- chunk_split(base64_encode($text)) . PHP_EOL;
- }
- public function add_body_file($file_name, $file_stream) {
- $this->body .= PHP_EOL . '--' . $this->mb . PHP_EOL .
- 'Content-Type: application/octet-stream; name="' . $file_name . '"' . PHP_EOL .
- 'Content-Disposition: attachment;' . PHP_EOL .
- ' filename="' . $file_name . '"' . PHP_EOL .
- 'Content-Transfer-Encoding: base64' . PHP_EOL . PHP_EOL . chunk_split(base64_encode($file_stream));
- }
- public function end_body() {
- return '--' . $this->mb . '--';
- }
- public function get_body() {
- return $this->body;
- }
- public function set_mb() {
- $this->mb = '_=_Multipart_Boundary_' . substr(md5(uniqid(time())), 0, 8);
- }
- public function set_subject($subject) {
- if ($subject) {
- $this->subject = $subject;
- }
- }
- public function get_subject() {
- return $this->subject;
- }
- public function get_mb() {
- return $this->mb;
- }
- public function set_header($email = 'No reply') {
- $this->header = 'Content-Type: multipart/mixed; boundary="' . $this->get_mb() . '"' . PHP_EOL . 'X-Mailer: PHP' . PHP_EOL . 'Reply-To: ' . $email . PHP_EOL;
- }
- public function get_header() {
- return $this->header;
- }
- }
Пример
- require('kmail.class.php');
- $mail = new KMail;
- $mail->set_subject('TESTUS');
- $mail->add_body_message('Test mail script');
- $mail->add_body_file('картинка.png', file_get_contents('mirror.png'));
- $mail->add_body_file('картинка2.png', file_get_contents('mirror2.png'));
- $mail->send();