Created
October 10, 2016 12:23
-
-
Save delphinpro/945266cd31584e0bceba778718d81ba3 to your computer and use it in GitHub Desktop.
Отправка письма с вложением.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * @since 10.10.2016 14:30 | |
| * @author delphinpro <delphinpro@gmail.com> | |
| * @copyright Copyright © 2016 delphinpro | |
| * @license Licensed under the MIT license | |
| */ | |
| error_reporting(0); | |
| //sleep(2); | |
| $emailTo = 'delphinpro@yandex.ru'; | |
| $emailFrom = 'delphinpro@gmail.com'; | |
| $subject = 'Заказ с сайта'; | |
| $uploadDir = 'upload'; | |
| $allowExtensions = array('jpg', 'jpeg', 'png', 'tiff', 'dwg', 'dwt', 'rar', 'zip', 'dws', 'dxf', 'pdf'); | |
| $maxSize = 10; // Mb | |
| if (!isset($_POST['form'])) { | |
| error('Нет данных'); | |
| } | |
| $uploadDir = __DIR__ . DIRECTORY_SEPARATOR . $uploadDir; | |
| switch ($_POST['form']) { | |
| case 'callback': | |
| $message = 'Заказ обратного звонка:' . PHP_EOL . PHP_EOL; | |
| $message .= 'Имя: ' . htmlspecialchars($_POST['name']) . PHP_EOL; | |
| $message .= 'Организация: ' . htmlspecialchars($_POST['org']) . PHP_EOL; | |
| $message .= 'Телефон: ' . htmlspecialchars($_POST['tel']) . PHP_EOL; | |
| send('Заказ обратного звонка', $message); | |
| break; | |
| case 'order': | |
| $message = 'Онлайн-Заказ с сайта:' . PHP_EOL . PHP_EOL; | |
| $message .= 'Имя: ' . htmlspecialchars($_POST['name']) . PHP_EOL; | |
| $message .= 'Организация: ' . htmlspecialchars($_POST['org']) . PHP_EOL; | |
| $message .= 'Телефон: ' . htmlspecialchars($_POST['tel']) . PHP_EOL; | |
| $message .= 'E-mail: ' . htmlspecialchars($_POST['email']) . PHP_EOL . PHP_EOL; | |
| $message .= 'Заказ: ' . htmlspecialchars($_POST['message']) . PHP_EOL; | |
| if (isset($_FILES) && isset($_FILES['file'])) { | |
| if (is_uploaded_file($_FILES['file']['tmp_name'])) { | |
| $filenameOriginal = $_FILES['file']['name']; | |
| $ext = strtolower(pathinfo($filenameOriginal, PATHINFO_EXTENSION)); | |
| $basename = pathinfo($filenameOriginal, PATHINFO_BASENAME); | |
| $filename = md5($basename) . '.' . $ext; | |
| if (!in_array($ext, $allowExtensions)) { | |
| error('Недопустимый формат файла. Допустимы следующие форматы: ' . join(',', $allowExtensions)); | |
| } | |
| if ((int)$_FILES['file']['size'] > $maxSize * 1024 * 1024) { | |
| error('Слишком большой размер файла. Максимум - ' . $maxSize . 'Mb.'); | |
| } | |
| move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . DIRECTORY_SEPARATOR . $filename); | |
| sendWithAttach('Онлайн-Заказ с сайта', $message, $filename, $filenameOriginal); | |
| } else { | |
| error('Файл не загружен'); | |
| } | |
| } else { | |
| send('Онлайн-Заказ с сайта', $message); | |
| } | |
| break; | |
| default: | |
| error('Неизвестная форма'); | |
| } | |
| /////////////////////////////////// | |
| function error($message = false) | |
| { | |
| $message = $message ? $message : 'Произошла ошибка. Попробуйте отправить данные еще раз.'; | |
| // echo $message.PHP_EOL; | |
| echo json_encode(array( | |
| 'error' => true, | |
| 'message' => $message, | |
| 'POST' => $_POST | |
| )); | |
| exit; | |
| } | |
| function send($subject, $message) | |
| { | |
| global $emailTo, $emailFrom; | |
| $headers = ''; | |
| $headers .= "Content-type: text/plain;charset=utf-8" . "\r\n"; | |
| $headers .= "From: $emailFrom" . "\r\n"; | |
| $result = mail($emailTo, $subject, $message, $headers); | |
| if ($result) { | |
| echo json_encode(array( | |
| 'error' => false, | |
| 'message' => 'Данные отправлены. Мы с вами свяжемся.' | |
| )); | |
| exit; | |
| } else { | |
| error('Ошибка отправки почты'); | |
| } | |
| exit; | |
| } | |
| function sendWithAttach($subject, $message, $filename, $filenameOriginal) | |
| { | |
| global $emailTo, $emailFrom, $uploadDir; | |
| $path = $uploadDir . DIRECTORY_SEPARATOR . $filename; | |
| $boundary = "--" . md5(uniqid(time())); | |
| $headers = "MIME-Version: 1.0;\r\n"; | |
| $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n"; | |
| $headers .= "From: $emailFrom <$emailFrom>" . "\r\n"; | |
| // первая часть само сообщение | |
| $multipart = "--$boundary\r\n"; | |
| $multipart .= "Content-Type: text/plain; charset=windows-1251\r\n"; | |
| $multipart .= "Content-Transfer-Encoding: base64\r\n"; | |
| $multipart .= "\r\n"; | |
| $multipart .= chunk_split(base64_encode(iconv("utf8", "windows-1251", $message))); | |
| // Закачиваем файл | |
| $fp = fopen($path, "r"); | |
| if (!$fp) { | |
| error("Не удается открыть файл"); | |
| } | |
| $file = fread($fp, filesize($path)); | |
| fclose($fp); | |
| // второй частью прикрепляем файл, можно прикрепить два и более файла | |
| $message_part = "\r\n--$boundary\r\n"; | |
| $message_part .= "Content-Type: application/octet-stream; name=\"$filenameOriginal\"\r\n"; | |
| $message_part .= "Content-Transfer-Encoding: base64\r\n"; | |
| $message_part .= "Content-Disposition: attachment; filename=\"$filenameOriginal\"\r\n"; | |
| $message_part .= "\r\n"; | |
| $message_part .= chunk_split(base64_encode($file)); | |
| $message_part .= "\r\n--$boundary--\r\n"; | |
| $multipart .= $message_part; | |
| $result = mail($emailTo, $subject, $multipart, $headers); | |
| if ($result) { | |
| echo json_encode(array( | |
| 'error' => false, | |
| 'message' => 'Данные отправлены. Мы с вами свяжемся.' | |
| )); | |
| //удаляем файлы через 60 сек. | |
| if (time_nanosleep(5, 0)) { | |
| unlink($path); | |
| } | |
| exit; | |
| } else { | |
| error('Ошибка отправки почты'); | |
| } | |
| } | |
| exit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment