forked from symfony/symfony
/
SmtpTransport.php
286 lines (240 loc) · 8.41 KB
/
SmtpTransport.php
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
277
278
279
280
281
282
283
284
285
286
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Mailer\Transport\Smtp;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Exception\LogicException;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\SmtpEnvelope;
use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mailer\Transport\Smtp\Stream\AbstractStream;
use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream;
use Symfony\Component\Mime\RawMessage;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
/**
* Sends emails over SMTP.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Chris Corbyn
*
* @experimental in 4.3
*/
class SmtpTransport extends AbstractTransport
{
private $started = false;
private $restartThreshold = 100;
private $restartThresholdSleep = 0;
private $restartCounter;
private $stream;
private $domain = '[127.0.0.1]';
public function __construct(AbstractStream $stream = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
{
parent::__construct($dispatcher, $logger);
$this->stream = $stream ?: new SocketStream();
}
public function getStream(): AbstractStream
{
return $this->stream;
}
/**
* Sets the maximum number of messages to send before re-starting the transport.
*
* By default, the threshold is set to 100 (and no sleep at restart).
*
* @param int $threshold The maximum number of messages (0 to disable)
* @param int $sleep The number of seconds to sleep between stopping and re-starting the transport
*/
public function setRestartThreshold(int $threshold, int $sleep = 0): self
{
$this->restartThreshold = $threshold;
$this->restartThresholdSleep = $sleep;
return $this;
}
/**
* Sets the name of the local domain that will be used in HELO.
*
* This should be a fully-qualified domain name and should be truly the domain
* you're using.
*
* If your server does not have a domain name, use the IP address. This will
* automatically be wrapped in square brackets as described in RFC 5321,
* section 4.1.3.
*/
public function setLocalDomain(string $domain): self
{
if ('' !== $domain && '[' !== $domain[0]) {
if (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$domain = '['.$domain.']';
} elseif (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$domain = '[IPv6:'.$domain.']';
}
}
$this->domain = $domain;
return $this;
}
/**
* Gets the name of the domain that will be used in HELO.
*
* If an IP address was specified, this will be returned wrapped in square
* brackets as described in RFC 5321, section 4.1.3.
*/
public function getLocalDomain(): string
{
return $this->domain;
}
public function send(RawMessage $message, SmtpEnvelope $envelope = null): ?SentMessage
{
$this->ping();
if (!$this->started) {
$this->start();
}
try {
$message = parent::send($message, $envelope);
} catch (TransportExceptionInterface $e) {
$this->executeCommand("RSET\r\n", [250]);
throw $e;
}
$this->checkRestartThreshold();
return $message;
}
/**
* Runs a command against the stream, expecting the given response codes.
*
* @param int[] $codes
*
* @return string The server response
*
* @throws TransportException when an invalid response if received
*
* @internal
*/
public function executeCommand(string $command, array $codes): string
{
$this->getLogger()->debug(sprintf('Email transport "%s" sent command "%s"', __CLASS__, trim($command)));
$this->stream->write($command);
$response = $this->getFullResponse();
$this->assertResponseCode($response, $codes);
return $response;
}
protected function doSend(SentMessage $message): void
{
$envelope = $message->getEnvelope();
$this->doMailFromCommand($envelope->getSender()->toString());
foreach ($envelope->getRecipients() as $recipient) {
$this->doRcptToCommand($recipient->toString());
}
$this->executeCommand("DATA\r\n", [354]);
foreach (AbstractStream::replace("\r\n.", "\r\n..", $message->toIterable()) as $chunk) {
$this->stream->write($chunk);
}
$this->stream->flush();
$this->executeCommand("\r\n.\r\n", [250]);
}
protected function doHeloCommand(): void
{
$this->executeCommand(sprintf("HELO %s\r\n", $this->domain), [250]);
}
private function doMailFromCommand($address): void
{
$this->executeCommand(sprintf("MAIL FROM:<%s>\r\n", $address), [250]);
}
private function doRcptToCommand($address): void
{
$this->executeCommand(sprintf("RCPT TO:<%s>\r\n", $address), [250, 251, 252]);
}
private function start(): void
{
if ($this->started) {
return;
}
$this->getLogger()->debug(sprintf('Email transport "%s" starting', __CLASS__));
$this->stream->initialize();
$this->assertResponseCode($this->getFullResponse(), [220]);
$this->doHeloCommand();
$this->started = true;
$this->getLogger()->debug(sprintf('Email transport "%s" started', __CLASS__));
}
private function stop(): void
{
if (!$this->started) {
return;
}
$this->getLogger()->debug(sprintf('Email transport "%s" stopping', __CLASS__));
try {
$this->executeCommand("QUIT\r\n", [221]);
} catch (TransportExceptionInterface $e) {
} finally {
$this->stream->terminate();
$this->started = false;
$this->getLogger()->debug(sprintf('Email transport "%s" stopped', __CLASS__));
}
}
private function ping(): void
{
if (!$this->started) {
return;
}
try {
$this->executeCommand("NOOP\r\n", [250]);
} catch (TransportExceptionInterface $e) {
$this->stop();
}
}
/**
* @throws TransportException if a response code is incorrect
*/
private function assertResponseCode(string $response, array $codes): void
{
if (!$codes) {
throw new LogicException('You must set the expected response code.');
}
if (!$response) {
throw new TransportException(sprintf('Expected response code "%s" but got an empty response.', implode('/', $codes)));
}
list($code) = sscanf($response, '%3d');
$valid = \in_array($code, $codes);
$this->getLogger()->debug(sprintf('Email transport "%s" received response "%s" (%s).', __CLASS__, trim($response), $valid ? 'ok' : 'error'));
if (!$valid) {
throw new TransportException(sprintf('Expected response code "%s" but got code "%s", with message "%s".', implode('/', $codes), $code, trim($response)), $code);
}
}
private function getFullResponse(): string
{
$response = '';
do {
$line = $this->stream->readLine();
$response .= $line;
} while ($line && isset($line[3]) && ' ' !== $line[3]);
return $response;
}
private function checkRestartThreshold(): void
{
// when using sendmail via non-interactive mode, the transport is never "started"
if (!$this->started) {
return;
}
++$this->restartCounter;
if ($this->restartCounter < $this->restartThreshold) {
return;
}
$this->stop();
if (0 < $sleep = $this->restartThresholdSleep) {
$this->getLogger()->debug(sprintf('Email transport "%s" sleeps for %d seconds after stopping', __CLASS__, $sleep));
sleep($sleep);
}
$this->start();
$this->restartCounter = 0;
}
public function __destruct()
{
$this->stop();
}
}