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

nette / mail / 20586072694

30 Dec 2025 12:48AM UTC coverage: 77.2% (-0.1%) from 77.336%
20586072694

push

github

dg
added CLAUDE.md

386 of 500 relevant lines covered (77.2%)

0.77 hits per line

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

95.42
/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
        public static array $defaultHeaders = [
42
                'MIME-Version' => '1.0',
43
                'X-Mailer' => 'Nette Framework',
44
        ];
45

46
        /** @var MimePart[] */
47
        private array $attachments = [];
48
        private array $inlines = [];
49
        private string $htmlBody = '';
50

51

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

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

61

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

71

72
        /**
73
         * Returns the sender of the message.
74
         */
75
        public function getFrom(): ?array
76
        {
77
                return $this->getHeader('From');
1✔
78
        }
79

80

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

90

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

100

101
        /**
102
         * Returns the subject of the message.
103
         */
104
        public function getSubject(): ?string
105
        {
106
                return $this->getHeader('Subject');
1✔
107
        }
108

109

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

119

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

129

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

139

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

154
                return [$email => $name];
1✔
155
        }
156

157

158
        /**
159
         * Sets the Return-Path header of the message.
160
         */
161
        public function setReturnPath(string $email): static
1✔
162
        {
163
                $this->setHeader('Return-Path', $email);
1✔
164
                return $this;
1✔
165
        }
166

167

168
        /**
169
         * Returns the Return-Path header.
170
         */
171
        public function getReturnPath(): ?string
172
        {
173
                return $this->getHeader('Return-Path');
×
174
        }
175

176

177
        /**
178
         * Sets email priority.
179
         */
180
        public function setPriority(int $priority): static
1✔
181
        {
182
                $this->setHeader('X-Priority', (string) $priority);
1✔
183
                return $this;
1✔
184
        }
185

186

187
        /**
188
         * Returns email priority.
189
         */
190
        public function getPriority(): ?int
191
        {
192
                $priority = $this->getHeader('X-Priority');
1✔
193
                return is_numeric($priority) ? (int) $priority : null;
1✔
194
        }
195

196

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

222
                                $html = substr_replace(
1✔
223
                                        $html,
1✔
224
                                        "{$m[1][0]}{$m[2][0]}cid:{$cids[$file]}",
1✔
225
                                        $m[0][1],
1✔
226
                                        strlen($m[0][0]),
1✔
227
                                );
228
                        }
229
                }
230

231
                if ($this->getSubject() == null) { // intentionally ==
1✔
232
                        $html = Strings::replace($html, '#<title>(.+?)</title>#is', function (array $m): void {
1✔
233
                                $this->setSubject(Nette\Utils\Html::htmlToText($m[1]));
1✔
234
                        });
1✔
235
                }
236

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

239
                if ($this->getBody() === '' && $html !== '') {
1✔
240
                        $this->setBody($this->buildText($html));
1✔
241
                }
242

243
                return $this;
1✔
244
        }
245

246

247
        /**
248
         * Gets HTML body.
249
         */
250
        public function getHtmlBody(): string
251
        {
252
                return $this->htmlBody;
1✔
253
        }
254

255

256
        /**
257
         * Adds embedded file.
258
         */
259
        public function addEmbeddedFile(string $file, ?string $content = null, ?string $contentType = null): MimePart
1✔
260
        {
261
                return $this->inlines[$file] = $this->createAttachment($file, $content, $contentType, 'inline')
1✔
262
                        ->setHeader('Content-ID', $this->getRandomId());
1✔
263
        }
264

265

266
        /**
267
         * Adds inlined Mime Part.
268
         */
269
        public function addInlinePart(MimePart $part): static
270
        {
271
                $this->inlines[] = $part;
×
272
                return $this;
×
273
        }
274

275

276
        /**
277
         * Adds attachment.
278
         */
279
        public function addAttachment(string $file, ?string $content = null, ?string $contentType = null): MimePart
1✔
280
        {
281
                return $this->attachments[] = $this->createAttachment($file, $content, $contentType, 'attachment');
1✔
282
        }
283

284

285
        /**
286
         * Gets all email attachments.
287
         * @return MimePart[]
288
         */
289
        public function getAttachments(): array
290
        {
291
                return $this->attachments;
×
292
        }
293

294

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

311
                if (!$contentType) {
1✔
312
                        $contentType = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content);
1✔
313
                }
314

315
                if (!strcasecmp($contentType, 'message/rfc822')) { // not allowed for attached files
1✔
316
                        $contentType = 'application/octet-stream';
1✔
317
                } elseif (!strcasecmp($contentType, 'image/svg')) { // Troublesome for some mailers...
1✔
318
                        $contentType = 'image/svg+xml';
×
319
                }
320

321
                $part->setBody($content);
1✔
322
                $part->setContentType($contentType);
1✔
323
                $part->setEncoding(preg_match('#(multipart|message)/#A', $contentType) ? self::Encoding8Bit : self::EncodingBase64);
1✔
324
                $part->setHeader('Content-Disposition', $disposition . '; filename="' . addcslashes($file, '"\\') . '"');
1✔
325
                return $part;
1✔
326
        }
327

328

329
        /********************* building and sending ****************d*g**/
330

331

332
        /**
333
         * Returns encoded message.
334
         */
335
        public function generateMessage(): string
336
        {
337
                return $this->build()->getEncodedMessage();
1✔
338
        }
339

340

341
        /**
342
         * Builds email. Does not modify itself, but returns a new object.
343
         */
344
        public function build(): static
345
        {
346
                $mail = clone $this;
1✔
347
                $mail->setHeader('Message-ID', $mail->getHeader('Message-ID') ?? $this->getRandomId());
1✔
348

349
                $cursor = $mail;
1✔
350
                if ($mail->attachments) {
1✔
351
                        $tmp = $cursor->setContentType('multipart/mixed');
1✔
352
                        $cursor = $cursor->addPart();
1✔
353
                        foreach ($mail->attachments as $value) {
1✔
354
                                $tmp->addPart($value);
1✔
355
                        }
356
                }
357

358
                if ($mail->htmlBody !== '') {
1✔
359
                        $tmp = $cursor->setContentType('multipart/alternative');
1✔
360
                        $cursor = $cursor->addPart();
1✔
361
                        $alt = $tmp->addPart();
1✔
362
                        if ($mail->inlines) {
1✔
363
                                $tmp = $alt->setContentType('multipart/related');
1✔
364
                                $alt = $alt->addPart();
1✔
365
                                foreach ($mail->inlines as $value) {
1✔
366
                                        $tmp->addPart($value);
1✔
367
                                }
368
                        }
369

370
                        $alt->setContentType('text/html', 'UTF-8')
1✔
371
                                ->setEncoding(preg_match('#[^\n]{990}#', $mail->htmlBody)
1✔
372
                                        ? self::EncodingQuotedPrintable
×
373
                                        : (preg_match('#[\x80-\xFF]#', $mail->htmlBody) ? self::Encoding8Bit : self::Encoding7Bit))
1✔
374
                                ->setBody($mail->htmlBody);
1✔
375
                }
376

377
                $text = $mail->getBody();
1✔
378
                $mail->setBody('');
1✔
379
                $cursor->setContentType('text/plain', 'UTF-8')
1✔
380
                        ->setEncoding(preg_match('#[^\n]{990}#', $text)
1✔
381
                                ? self::EncodingQuotedPrintable
1✔
382
                                : (preg_match('#[\x80-\xFF]#', $text) ? self::Encoding8Bit : self::Encoding7Bit))
1✔
383
                        ->setBody($text);
1✔
384

385
                return $mail;
1✔
386
        }
387

388

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

407

408
        private function getRandomId(): string
409
        {
410
                return '<' . Nette\Utils\Random::generate() . '@'
1✔
411
                        . preg_replace('#[^\w.-]+#', '', $_SERVER['HTTP_HOST'] ?? php_uname('n'))
1✔
412
                        . '>';
1✔
413
        }
414
}
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