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

nette / mail / 21815465112

09 Feb 2026 07:00AM UTC coverage: 77.2%. Remained the same
21815465112

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
        /** @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): void {
1✔
238
                                $this->setSubject(Nette\Utils\Html::htmlToText($m[1]));
1✔
239
                        });
1✔
240
                }
241

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

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

248
                return $this;
1✔
249
        }
250

251

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

260

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

270

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

280

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

289

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

299

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

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

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

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

333

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

336

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

345

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

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

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

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

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

390
                return $mail;
1✔
391
        }
392

393

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

412

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