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

nette / mail / 20837253071

09 Jan 2026 12:49AM UTC coverage: 77.2%. Remained the same
20837253071

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

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

53

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

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

63

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

73

74
        /**
75
         * Returns the sender of the message.
76
         * @return array<string, ?string>|null
77
         */
78
        public function getFrom(): ?array
79
        {
80
                return $this->getHeader('From');
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
                return $this->getHeader('Subject');
1✔
110
        }
111

112

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

122

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

132

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

142

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

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

161

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

171

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

180

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

190

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

200

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

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

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

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

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

247
                return $this;
1✔
248
        }
249

250

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

259

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

269

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

279

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

288

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

298

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

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

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

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

332

333
        /********************* building and sending ****************d*g**/
334

335

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

344

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

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

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

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

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

389
                return $mail;
1✔
390
        }
391

392

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

411

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