forked from Ipatov/SendMailSmtpClass
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSendMailSmtpClass.php
More file actions
276 lines (245 loc) · 9.93 KB
/
SendMailSmtpClass.php
File metadata and controls
276 lines (245 loc) · 9.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
<?php
/**
* SendMailSmtpClass
*
* Класс для отправки писем через SMTP с авторизацией
* Может работать через SSL протокол
* Тестировалось на почтовых серверах yandex.ru, mail.ru и gmail.com, smtp.beget.com
*
* v 1.1
* Добавлено:
* - Приветствие сервера ehlo в приоритете, если не сервер не ответил, то шлется helo
* - Работа с кодировками utf-8 и windows-1251
* - Возможность отправки нескольким получателям
* - Автоматическое формирование заголовков письма
* - Возможность вложения файлов в письмо
*
* @author Ipatov Evgeniy <admin@vk-book.ru>
* @version 1.1
*/
class SendMailSmtpClass {
/**
*
* @var string $smtp_username - логин
* @var string $smtp_password - пароль
* @var string $smtp_host - хост
* @var array $smtp_from - от кого
* @var integer $smtp_port - порт
* @var string $smtp_charset - кодировка
* @var string $boundary - разделитель содержимого письма(для отправки файлов)
* @var bool $addFile - содержит письмо файл или нет
* @var string $multipart - заголовки для письма с файлами
* @var array $arrayCC - массив получателей копии письма
* @var array $arrayBCC - массив получателей скрытой копии письма
*
*/
public $smtp_username;
public $smtp_password;
public $smtp_host;
public $smtp_from;
public $smtp_port;
public $smtp_charset;
public $boundary;
public $addFile = false;
public $multipart;
public $arrayCC;
public $arrayBCC;
public function __construct($smtp_username, $smtp_password, $smtp_host, $smtp_port = 25, $smtp_charset = "utf-8") {
$this->smtp_username = $smtp_username;
$this->smtp_password = $smtp_password;
$this->smtp_host = $smtp_host;
$this->smtp_port = $smtp_port;
$this->smtp_charset = $smtp_charset;
// разделитель файлов
$this->boundary = "--".md5(uniqid(time()));
$this->multipart = "";
}
/**
* Отправка письма
*
* @param string $mailTo - получатель письма
* @param string $subject - тема письма
* @param string $message - тело письма
* @param array $smtp_from - отправитель. Массив с именем и e-mail
*
* @return bool|string В случаи отправки вернет true, иначе текст ошибки
*
*/
function send($mailTo, $subject, $message, $smtp_from) {
// подготовка содержимого письма к отправке
$contentMail = $this->getContentMail($subject, $message, $smtp_from, $mailTo);
try {
if(!$socket = @fsockopen($this->smtp_host, $this->smtp_port, $errorNumber, $errorDescription, 30)){
throw new Exception($errorNumber.".".$errorDescription);
}
if (!$this->_parseServer($socket, "220")){
throw new Exception('Connection error');
}
$server_name = $_SERVER["SERVER_NAME"];
fputs($socket, "EHLO $server_name\r\n");
if(!$this->_parseServer($socket, "250")){
// если сервер не ответил на EHLO, то отправляем HELO
fputs($socket, "HELO $server_name\r\n");
if (!$this->_parseServer($socket, "250")) {
fclose($socket);
throw new Exception('Error of command sending: HELO');
}
}
fputs($socket, "AUTH LOGIN\r\n");
if (!$this->_parseServer($socket, "334")) {
fclose($socket);
throw new Exception('Autorization error');
}
fputs($socket, base64_encode($this->smtp_username) . "\r\n");
if (!$this->_parseServer($socket, "334")) {
fclose($socket);
throw new Exception('Autorization error');
}
fputs($socket, base64_encode($this->smtp_password) . "\r\n");
if (!$this->_parseServer($socket, "235")) {
fclose($socket);
throw new Exception('Autorization error');
}
fputs($socket, "MAIL FROM: <".$this->smtp_username.">\r\n");
if (!$this->_parseServer($socket, "250")) {
fclose($socket);
throw new Exception('Error of command sending: MAIL FROM');
}
$mailTo = str_replace(" ", "", $mailTo);
$emails_to_array = explode(',', $mailTo);
foreach($emails_to_array as $email) {
fputs($socket, "RCPT TO: <{$email}>\r\n");
if (!$this->_parseServer($socket, "250")) {
fclose($socket);
throw new Exception('Error of command sending: RCPT TO');
}
}
// если есть кому отправить копию
if(!empty($this->arrayCC)){
foreach($this->arrayCC as $emailCC) {
fputs($socket, "RCPT TO: <{$emailCC}>\r\n");
if (!$this->_parseServer($socket, "250")) {
fclose($socket);
throw new Exception('Error of command sending: RCPT TO');
}
}
}
// если есть кому отправить скрытую копию
if(!empty($this->arrayBCC)){
foreach($this->arrayBCC as $emailBCC) {
fputs($socket, "RCPT TO: <{$emailBCC}>\r\n");
if (!$this->_parseServer($socket, "250")) {
fclose($socket);
throw new Exception('Error of command sending: RCPT TO');
}
}
}
fputs($socket, "DATA\r\n");
if (!$this->_parseServer($socket, "354")) {
fclose($socket);
throw new Exception('Error of command sending: DATA');
}
fputs($socket, $contentMail."\r\n.\r\n");
if (!$this->_parseServer($socket, "250")) {
fclose($socket);
throw new Exception("E-mail didn't sent");
}
fputs($socket, "QUIT\r\n");
fclose($socket);
} catch (Exception $e) {
return $e->getMessage();
}
return true;
}
// добавление файла в письмо
public function addFile($path){
$file = @fopen($path, "rb");
if(!$file) {
throw new Exception("File `{$path}` didn't open");
}
$data = fread($file, filesize( $path ) );
fclose($file);
$filename = basename($path);
$multipart = "\r\n--{$this->boundary}\r\n";
$multipart .= "Content-Type: application/octet-stream; name=\"$filename\"\r\n";
$multipart .= "Content-Transfer-Encoding: base64\r\n";
$multipart .= "Content-Disposition: attachment; filename=\"$filename\"\r\n";
$multipart .= "\r\n";
$multipart .= chunk_split(base64_encode($data));
$this->multipart .= $multipart;
$this->addFile = true;
}
// парсинг ответа сервера
private function _parseServer($socket, $response) {
$responseServer = $response;
while (@substr($responseServer, 3, 1) != ' ') {
if (!($responseServer = fgets($socket, 256))) {
return false;
}
}
if (!(substr($responseServer, 0, 3) == $response)) {
return false;
}
return true;
}
// подготовка содержимого письма
private function getContentMail($subject, $message, $smtp_from, $mailTo){
// если кодировка windows-1251, то перекодируем тему
if( strtolower($this->smtp_charset) == "windows-1251" ){
$subject = iconv('utf-8', 'windows-1251', $subject);
}
$contentMail = "Date: " . date("D, d M Y H:i:s") . " UT\r\n";
$contentMail .= 'Subject: =?' . $this->smtp_charset . '?B?' . base64_encode($subject) . "=?=\r\n";
// заголовок письма
$headers = "MIME-Version: 1.0\r\n";
// кодировка письма
if($this->addFile){
// если есть файлы
$headers .= "Content-Type: multipart/mixed; boundary=\"{$this->boundary}\"\r\n";
}else{
$headers .= "Content-type: text/html; charset={$this->smtp_charset}\r\n";
}
$headers .= "From: {$smtp_from[0]} <{$smtp_from[1]}>\r\n"; // от кого письмо
$headers.= "To: ".$mailTo."\r\n"; // кому
// если есть кому отправить копию
if(!empty($this->arrayCC)){
foreach($this->arrayCC as $emailCC) {
$headers.= "Cc: ".$emailCC."\r\n"; // кому копию
}
}
// если есть кому отправить копию
if(!empty($this->arrayBCC)){
foreach($this->arrayBCC as $emailBCC) {
$headers.= "Bcc: ".$emailBCC."\r\n"; // кому копию
}
}
$contentMail .= $headers . "\r\n";
if($this->addFile){
// если есть файлы
$multipart = "--{$this->boundary}\r\n";
$multipart .= "Content-Type: text/html; charset=utf-8\r\n";
$multipart .= "Content-Transfer-Encoding: base64\r\n";
$multipart .= "\r\n";
$multipart .= chunk_split(base64_encode($message));
// файлы
$multipart .= $this->multipart;
$multipart .= "\r\n--{$this->boundary}--\r\n";
$contentMail .= $multipart;
}else{
$contentMail .= $message . "\r\n";
}
// если кодировка windows-1251, то все письмо перекодируем
if( strtolower($this->smtp_charset) == "windows-1251" ){
$contentMail = iconv('utf-8', 'windows-1251', $contentMail);
}
return $contentMail;
}
// добавлении получателя копии
public function toCopy($email){
$this->arrayCC[] = $email;
}
// добавлении получателя скрытой копии
public function toHideCopy($email){
$this->arrayBCC[] = $email;
}
}