• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / mail / 22359399110

24 Feb 2026 04:11PM UTC coverage: 76.863%. Remained the same
22359399110

push

github

dg
fixed PHPStan errors WIP

31 of 45 new or added lines in 5 files covered. (68.89%)

64 existing lines in 6 files now uncovered.

392 of 510 relevant lines covered (76.86%)

0.77 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.93
/src/Mail/Message.php
1
<?php declare(strict_types=1);
1✔
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace Nette\Mail;
9

10
use Nette;
11
use Nette\Utils\Strings;
12
use function addcslashes, array_map, array_reverse, basename, date, explode, finfo_buffer, finfo_open, implode, is_array, is_numeric, is_string, ltrim, php_uname, preg_match, preg_replace, rtrim, str_replace, strcasecmp, stripslashes, strlen, substr, substr_replace, trim, urldecode;
13
use const FILEINFO_MIME_TYPE;
14

15

16
/**
17
 * Mail provides functionality to compose and send both text and MIME-compliant multipart email messages.
18
 *
19
 * @property-deprecated   string $subject
20
 * @property-deprecated   string $htmlBody
21
 */
22
class Message extends MimePart
23
{
24
        /** Priority */
25
        public const
26
                High = 1,
27
                Normal = 3,
28
                Low = 5;
29

30
        #[\Deprecated('use Message::High')]
31
        public const HIGH = self::High;
32

33
        #[\Deprecated('use Message::Normal')]
34
        public const NORMAL = self::Normal;
35

36
        #[\Deprecated('use Message::Low')]
37
        public const LOW = self::Low;
38

39
        /** @var array<string, string> */
40
        public static array $defaultHeaders = [
41
                'MIME-Version' => '1.0',
42
                'X-Mailer' => 'Nette Framework',
43
        ];
44

45
        /** @var list<MimePart> */
46
        private array $attachments = [];
47

48
        /** @var array<MimePart> */
49
        private array $inlines = [];
50
        private string $htmlBody = '';
51

52

53
        public function __construct()
54
        {
55
                foreach (static::$defaultHeaders as $name => $value) {
1✔
56
                        $this->setHeader($name, $value);
1✔
57
                }
58

59
                $this->setHeader('Date', date('r'));
1✔
60
        }
1✔
61

62

63
        /**
64
         * Sets the sender of the message. Email or format "John Doe" <doe@example.com>
65
         */
66
        public function setFrom(string $email, ?string $name = null): static
1✔
67
        {
68
                $this->setHeader('From', $this->formatEmail($email, $name));
1✔
69
                return $this;
1✔
70
        }
71

72

73
        /**
74
         * Returns the sender of the message.
75
         * @return ?array<string, ?string>
76
         */
77
        public function getFrom(): ?array
78
        {
79
                $value = $this->getHeader('From');
1✔
80
                return is_array($value) ? $value : null;
1✔
81
        }
82

83

84
        /**
85
         * Adds the reply-to address. Email or format "John Doe" <doe@example.com>
86
         */
87
        public function addReplyTo(string $email, ?string $name = null): static
1✔
88
        {
89
                $this->setHeader('Reply-To', $this->formatEmail($email, $name), append: true);
1✔
90
                return $this;
1✔
91
        }
92

93

94
        /**
95
         * Sets the subject of the message.
96
         */
97
        public function setSubject(string $subject): static
1✔
98
        {
99
                $this->setHeader('Subject', $subject);
1✔
100
                return $this;
1✔
101
        }
102

103

104
        /**
105
         * Returns the subject of the message.
106
         */
107
        public function getSubject(): ?string
108
        {
109
                $value = $this->getHeader('Subject');
1✔
110
                return is_string($value) ? $value : null;
1✔
111
        }
112

113

114
        /**
115
         * Adds email recipient. Email or format "John Doe" <doe@example.com>
116
         */
117
        public function addTo(string $email, ?string $name = null): static // addRecipient()
1✔
118
        {
119
                $this->setHeader('To', $this->formatEmail($email, $name), append: true);
1✔
120
                return $this;
1✔
121
        }
122

123

124
        /**
125
         * Adds carbon copy email recipient. Email or format "John Doe" <doe@example.com>
126
         */
127
        public function addCc(string $email, ?string $name = null): static
1✔
128
        {
129
                $this->setHeader('Cc', $this->formatEmail($email, $name), append: true);
1✔
130
                return $this;
1✔
131
        }
132

133

134
        /**
135
         * Adds blind carbon copy email recipient. Email or format "John Doe" <doe@example.com>
136
         */
137
        public function addBcc(string $email, ?string $name = null): static
1✔
138
        {
139
                $this->setHeader('Bcc', $this->formatEmail($email, $name), append: true);
1✔
140
                return $this;
1✔
141
        }
142

143

144
        /**
145
         * Formats recipient email.
146
         * @return array<string, ?string>
147
         */
148
        private function formatEmail(string $email, ?string $name = null): array
1✔
149
        {
150
                if (!$name && preg_match('#^(.+) +<(.*)>$#D', $email, $matches)) {
1✔
151
                        [, $name, $email] = $matches;
1✔
152
                        $name = stripslashes($name);
1✔
153
                        $tmp = substr($name, 1, -1);
1✔
154
                        if ($name === '"' . $tmp . '"') {
1✔
155
                                $name = $tmp;
1✔
156
                        }
157
                }
158

159
                return [$email => $name];
1✔
160
        }
161

162

163
        /**
164
         * Sets the Return-Path header of the message.
165
         */
166
        public function setReturnPath(string $email): static
1✔
167
        {
168
                $this->setHeader('Return-Path', $email);
1✔
169
                return $this;
1✔
170
        }
171

172

173
        /**
174
         * Returns the Return-Path header.
175
         */
176
        public function getReturnPath(): ?string
177
        {
NEW
178
                $value = $this->getHeader('Return-Path');
×
NEW
179
                return is_string($value) ? $value : null;
×
180
        }
181

182

183
        /**
184
         * Sets email priority.
185
         */
186
        public function setPriority(int $priority): static
1✔
187
        {
188
                $this->setHeader('X-Priority', (string) $priority);
1✔
189
                return $this;
1✔
190
        }
191

192

193
        /**
194
         * Returns email priority.
195
         */
196
        public function getPriority(): ?int
197
        {
198
                $priority = $this->getHeader('X-Priority');
1✔
199
                return is_numeric($priority) ? (int) $priority : null;
1✔
200
        }
201

202

203
        /**
204
         * Sets HTML body.
205
         */
206
        public function setHtmlBody(string $html, ?string $basePath = null): static
1✔
207
        {
208
                if ($basePath) {
1✔
209
                        $cids = [];
1✔
210
                        $matches = Strings::matchAll(
1✔
211
                                $html,
1✔
212
                                '#
1✔
213
                                        (<img[^<>]*\s src\s*=\s*
214
                                        |<body[^<>]*\s background\s*=\s*
215
                                        |<[^<>]+\s style\s*=\s* ["\'][^"\'>]+[:\s] url\(
216
                                        |<style[^>]*>[^<]+ [:\s] url\()
217
                                        (["\']?)(?![a-z]+:|[/\#])([^"\'>)\s]+)
218
                                        |\[\[ ([\w()+./@~-]+) \]\]
219
                                #ix',
220
                                captureOffset: true,
1✔
221
                        );
222
                        foreach (array_reverse($matches) as $m) {
1✔
223
                                $file = rtrim($basePath, '/\\') . '/' . (isset($m[4]) ? $m[4][0] : urldecode($m[3][0]));
1✔
224
                                if (!isset($cids[$file])) {
1✔
225
                                        $contentId = $this->addEmbeddedFile($file)->getHeader('Content-ID');
1✔
226
                                        $cids[$file] = is_string($contentId) ? substr($contentId, 1, -1) : '';
1✔
227
                                }
228

229
                                $html = substr_replace(
1✔
230
                                        $html,
1✔
231
                                        "{$m[1][0]}{$m[2][0]}cid:{$cids[$file]}",
1✔
232
                                        $m[0][1],
1✔
233
                                        strlen($m[0][0]),
1✔
234
                                );
235
                        }
236
                }
237

238
                if ($this->getSubject() == null) { // intentionally ==
1✔
239
                        $html = Strings::replace($html, '#<title>(.+?)</title>#is', function (array $m): void {
1✔
240
                                $this->setSubject(Nette\Utils\Html::htmlToText($m[1]));
1✔
241
                        });
1✔
242
                }
243

244
                $this->htmlBody = ltrim(str_replace("\r", '', $html), "\n");
1✔
245

246
                if ($this->getBody() === '' && $html !== '') {
1✔
247
                        $this->setBody($this->buildText($html));
1✔
248
                }
249

250
                return $this;
1✔
251
        }
252

253

254
        /**
255
         * Gets HTML body.
256
         */
257
        public function getHtmlBody(): string
258
        {
259
                return $this->htmlBody;
1✔
260
        }
261

262

263
        /**
264
         * Adds embedded file.
265
         */
266
        public function addEmbeddedFile(string $file, ?string $content = null, ?string $contentType = null): MimePart
1✔
267
        {
268
                return $this->inlines[$file] = $this->createAttachment($file, $content, $contentType, 'inline')
1✔
269
                        ->setHeader('Content-ID', $this->getRandomId());
1✔
270
        }
271

272

273
        /**
274
         * Adds inlined Mime Part.
275
         */
276
        public function addInlinePart(MimePart $part): static
277
        {
UNCOV
278
                $this->inlines[] = $part;
×
UNCOV
279
                return $this;
×
280
        }
281

282

283
        /**
284
         * Adds attachment.
285
         */
286
        public function addAttachment(string $file, ?string $content = null, ?string $contentType = null): MimePart
1✔
287
        {
288
                return $this->attachments[] = $this->createAttachment($file, $content, $contentType, 'attachment');
1✔
289
        }
290

291

292
        /**
293
         * Gets all email attachments.
294
         * @return list<MimePart>
295
         */
296
        public function getAttachments(): array
297
        {
UNCOV
298
                return $this->attachments;
×
299
        }
300

301

302
        /**
303
         * Creates file MIME part.
304
         */
305
        private function createAttachment(
1✔
306
                string $file,
307
                ?string $content,
308
                ?string $contentType,
309
                string $disposition,
310
        ): MimePart
311
        {
312
                $part = new MimePart;
1✔
313
                if ($content === null) {
1✔
314
                        $content = Nette\Utils\FileSystem::read($file);
1✔
315
                        $file = Strings::fixEncoding(basename($file));
1✔
316
                }
317

318
                if (!$contentType) {
1✔
319
                        $finfo = finfo_open(FILEINFO_MIME_TYPE);
1✔
320
                        $contentType = $finfo ? finfo_buffer($finfo, $content) : false;
1✔
321
                        $contentType = $contentType ?: 'application/octet-stream';
1✔
322
                }
323

324
                if (!strcasecmp($contentType, 'message/rfc822')) { // not allowed for attached files
1✔
325
                        $contentType = 'application/octet-stream';
1✔
326
                } elseif (!strcasecmp($contentType, 'image/svg')) { // Troublesome for some mailers...
1✔
UNCOV
327
                        $contentType = 'image/svg+xml';
×
328
                }
329

330
                $part->setBody($content);
1✔
331
                $part->setContentType($contentType);
1✔
332
                $part->setEncoding(preg_match('#(multipart|message)/#A', $contentType) ? self::Encoding8Bit : self::EncodingBase64);
1✔
333
                $part->setHeader('Content-Disposition', $disposition . '; filename="' . addcslashes($file, '"\\') . '"');
1✔
334
                return $part;
1✔
335
        }
336

337

338
        /********************* building and sending ****************d*g**/
339

340

341
        /**
342
         * Returns encoded message.
343
         */
344
        public function generateMessage(): string
345
        {
346
                return $this->build()->getEncodedMessage();
1✔
347
        }
348

349

350
        /**
351
         * Builds email. Does not modify itself, but returns a new object.
352
         */
353
        public function build(): static
354
        {
355
                $mail = clone $this;
1✔
356
                $mail->setHeader('Message-ID', $mail->getHeader('Message-ID') ?? $this->getRandomId());
1✔
357

358
                $cursor = $mail;
1✔
359
                if ($mail->attachments) {
1✔
360
                        $tmp = $cursor->setContentType('multipart/mixed');
1✔
361
                        $cursor = $cursor->addPart();
1✔
362
                        foreach ($mail->attachments as $value) {
1✔
363
                                $tmp->addPart($value);
1✔
364
                        }
365
                }
366

367
                if ($mail->htmlBody !== '') {
1✔
368
                        $tmp = $cursor->setContentType('multipart/alternative');
1✔
369
                        $cursor = $cursor->addPart();
1✔
370
                        $alt = $tmp->addPart();
1✔
371
                        if ($mail->inlines) {
1✔
372
                                $tmp = $alt->setContentType('multipart/related');
1✔
373
                                $alt = $alt->addPart();
1✔
374
                                foreach ($mail->inlines as $value) {
1✔
375
                                        $tmp->addPart($value);
1✔
376
                                }
377
                        }
378

379
                        $alt->setContentType('text/html', 'UTF-8')
1✔
380
                                ->setEncoding(preg_match('#[^\n]{990}#', $mail->htmlBody)
1✔
UNCOV
381
                                        ? self::EncodingQuotedPrintable
×
382
                                        : (preg_match('#[\x80-\xFF]#', $mail->htmlBody) ? self::Encoding8Bit : self::Encoding7Bit))
1✔
383
                                ->setBody($mail->htmlBody);
1✔
384
                }
385

386
                $text = $mail->getBody();
1✔
387
                $mail->setBody('');
1✔
388
                $cursor->setContentType('text/plain', 'UTF-8')
1✔
389
                        ->setEncoding(preg_match('#[^\n]{990}#', $text)
1✔
390
                                ? self::EncodingQuotedPrintable
1✔
391
                                : (preg_match('#[\x80-\xFF]#', $text) ? self::Encoding8Bit : self::Encoding7Bit))
1✔
392
                        ->setBody($text);
1✔
393

394
                return $mail;
1✔
395
        }
396

397

398
        /**
399
         * Builds text content.
400
         */
401
        protected function buildText(string $html): string
1✔
402
        {
403
                $html = Strings::replace($html, [
1✔
404
                        '#<(style|script|head).*</\1>#Uis' => '',
1✔
405
                        '#<t[dh][ >]#i' => ' $0',
406
                        '#<a\s[^>]*href=(?|"([^"]+)"|\'([^\']+)\')[^>]*>(.*?)</a>#is' => '$2 &lt;$1&gt;',
407
                        '#[\r\n]+#' => ' ',
408
                        '#<(/?p|/?h\d|li|br|/tr)[ >/]#i' => "\n$0",
409
                ]);
410
                $text = Nette\Utils\Html::htmlToText($html);
1✔
411
                $text = Strings::replace($text, '#[ \t]+#', ' ');
1✔
412
                $text = implode("\n", array_map('trim', explode("\n", $text)));
1✔
413
                return trim($text);
1✔
414
        }
415

416

417
        private function getRandomId(): string
418
        {
419
                return '<' . Nette\Utils\Random::generate() . '@'
1✔
420
                        . preg_replace('#[^\w.-]+#', '', $_SERVER['HTTP_HOST'] ?? php_uname('n'))
1✔
421
                        . '>';
1✔
422
        }
423
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc