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

nette / mail / 21849714861

10 Feb 2026 02:48AM UTC coverage: 77.246% (+0.05%) from 77.2%
21849714861

push

github

dg
added CLAUDE.md

387 of 501 relevant lines covered (77.25%)

0.77 hits per line

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

95.45
/src/Mail/Message.php
1
<?php
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
declare(strict_types=1);
9

10
namespace Nette\Mail;
11

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

17

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

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

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

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

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

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

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

54

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

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

64

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

74

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

84

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

94

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

104

105
        /**
106
         * Returns the subject of the message.
107
         */
108
        public function getSubject(): ?string
109
        {
110
                return $this->getHeader('Subject');
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
        {
178
                return $this->getHeader('Return-Path');
×
179
        }
180

181

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

191

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

201

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

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

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

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

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

249
                return $this;
1✔
250
        }
251

252

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

261

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

271

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

281

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

290

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

300

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

317
                if (!$contentType) {
1✔
318
                        $contentType = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content);
1✔
319
                }
320

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

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

334

335
        /********************* building and sending ****************d*g**/
336

337

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

346

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

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

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

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

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

391
                return $mail;
1✔
392
        }
393

394

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

413

414
        private function getRandomId(): string
415
        {
416
                return '<' . Nette\Utils\Random::generate() . '@'
1✔
417
                        . preg_replace('#[^\w.-]+#', '', $_SERVER['HTTP_HOST'] ?? php_uname('n'))
1✔
418
                        . '>';
1✔
419
        }
420
}
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