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

nette / mail / 22836180643

09 Mar 2026 02:43AM UTC coverage: 77.2%. Remained the same
22836180643

push

github

dg
improved PHPDoc descriptions

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 declare(strict_types=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_numeric, ltrim, php_uname, preg_match, preg_replace, rtrim, str_replace, strcasecmp, stripslashes, strlen, substr, substr_replace, trim, urldecode;
13

14

15
/**
16
 * Represents an email message with support for HTML body, attachments, and embedded files.
17
 *
18
 * @property-deprecated   string $subject
19
 * @property-deprecated   string $htmlBody
20
 */
21
class Message extends MimePart
22
{
23
        /** Priority */
24
        public const
25
                High = 1,
26
                Normal = 3,
27
                Low = 5;
28

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

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

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

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

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

47
        /** @var array<MimePart> */
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
         * @return ?array<string, ?string>
75
         */
76
        public function getFrom(): ?array
77
        {
78
                return $this->getHeader('From');
1✔
79
        }
80

81

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

91

92
        public function setSubject(string $subject): static
1✔
93
        {
94
                $this->setHeader('Subject', $subject);
1✔
95
                return $this;
1✔
96
        }
97

98

99
        public function getSubject(): ?string
100
        {
101
                return $this->getHeader('Subject');
1✔
102
        }
103

104

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

114

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

124

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

134

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

150
                return [$email => $name];
1✔
151
        }
152

153

154
        public function setReturnPath(string $email): static
1✔
155
        {
156
                $this->setHeader('Return-Path', $email);
1✔
157
                return $this;
1✔
158
        }
159

160

161
        public function getReturnPath(): ?string
162
        {
163
                return $this->getHeader('Return-Path');
×
164
        }
165

166

167
        public function setPriority(int $priority): static
1✔
168
        {
169
                $this->setHeader('X-Priority', (string) $priority);
1✔
170
                return $this;
1✔
171
        }
172

173

174
        public function getPriority(): ?int
175
        {
176
                $priority = $this->getHeader('X-Priority');
1✔
177
                return is_numeric($priority) ? (int) $priority : null;
1✔
178
        }
179

180

181
        /**
182
         * Sets HTML body. If $basePath is provided, local images referenced in the HTML
183
         * are automatically embedded as inline attachments with their src rewritten to cid: URIs.
184
         * Also sets the subject from the HTML <title> if not already set, and auto-generates a plain-text alternative.
185
         */
186
        public function setHtmlBody(string $html, ?string $basePath = null): static
1✔
187
        {
188
                if ($basePath) {
1✔
189
                        $cids = [];
1✔
190
                        $matches = Strings::matchAll(
1✔
191
                                $html,
1✔
192
                                '#
1✔
193
                                        (<img[^<>]*\s src\s*=\s*
194
                                        |<body[^<>]*\s background\s*=\s*
195
                                        |<[^<>]+\s style\s*=\s* ["\'][^"\'>]+[:\s] url\(
196
                                        |<style[^>]*>[^<]+ [:\s] url\()
197
                                        (["\']?)(?![a-z]+:|[/\#])([^"\'>)\s]+)
198
                                        |\[\[ ([\w()+./@~-]+) \]\]
199
                                #ix',
200
                                captureOffset: true,
1✔
201
                        );
202
                        foreach (array_reverse($matches) as $m) {
1✔
203
                                $file = rtrim($basePath, '/\\') . '/' . (isset($m[4]) ? $m[4][0] : urldecode($m[3][0]));
1✔
204
                                if (!isset($cids[$file])) {
1✔
205
                                        $cids[$file] = substr($this->addEmbeddedFile($file)->getHeader('Content-ID'), 1, -1);
1✔
206
                                }
207

208
                                $html = substr_replace(
1✔
209
                                        $html,
1✔
210
                                        "{$m[1][0]}{$m[2][0]}cid:{$cids[$file]}",
1✔
211
                                        $m[0][1],
1✔
212
                                        strlen($m[0][0]),
1✔
213
                                );
214
                        }
215
                }
216

217
                if ($this->getSubject() == null) { // intentionally ==
1✔
218
                        $html = Strings::replace($html, '#<title>(.+?)</title>#is', function (array $m): void {
1✔
219
                                $this->setSubject(Nette\Utils\Html::htmlToText($m[1]));
1✔
220
                        });
1✔
221
                }
222

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

225
                if ($this->getBody() === '' && $html !== '') {
1✔
226
                        $this->setBody($this->buildText($html));
1✔
227
                }
228

229
                return $this;
1✔
230
        }
231

232

233
        public function getHtmlBody(): string
234
        {
235
                return $this->htmlBody;
1✔
236
        }
237

238

239
        /**
240
         * Adds an embedded (inline) file. If $content is null, the file is read from disk.
241
         * In that case $file is the path; otherwise $file is used as the filename.
242
         */
243
        public function addEmbeddedFile(string $file, ?string $content = null, ?string $contentType = null): MimePart
1✔
244
        {
245
                return $this->inlines[$file] = $this->createAttachment($file, $content, $contentType, 'inline')
1✔
246
                        ->setHeader('Content-ID', $this->getRandomId());
1✔
247
        }
248

249

250
        /**
251
         * Adds a pre-built MIME part as an inline (embedded) attachment.
252
         */
253
        public function addInlinePart(MimePart $part): static
254
        {
255
                $this->inlines[] = $part;
×
256
                return $this;
×
257
        }
258

259

260
        /**
261
         * Adds an attachment. If $content is null, the file is read from disk.
262
         * In that case $file is the path; otherwise $file is used as the filename.
263
         */
264
        public function addAttachment(string $file, ?string $content = null, ?string $contentType = null): MimePart
1✔
265
        {
266
                return $this->attachments[] = $this->createAttachment($file, $content, $contentType, 'attachment');
1✔
267
        }
268

269

270
        /**
271
         * @return list<MimePart>
272
         */
273
        public function getAttachments(): array
274
        {
275
                return $this->attachments;
×
276
        }
277

278

279
        /**
280
         * Creates file MIME part.
281
         */
282
        private function createAttachment(
1✔
283
                string $file,
284
                ?string $content,
285
                ?string $contentType,
286
                string $disposition,
287
        ): MimePart
288
        {
289
                $part = new MimePart;
1✔
290
                if ($content === null) {
1✔
291
                        $content = Nette\Utils\FileSystem::read($file);
1✔
292
                        $file = Strings::fixEncoding(basename($file));
1✔
293
                }
294

295
                if (!$contentType) {
1✔
296
                        $contentType = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content);
1✔
297
                }
298

299
                if (!strcasecmp($contentType, 'message/rfc822')) { // not allowed for attached files
1✔
300
                        $contentType = 'application/octet-stream';
1✔
301
                } elseif (!strcasecmp($contentType, 'image/svg')) { // Troublesome for some mailers...
1✔
302
                        $contentType = 'image/svg+xml';
×
303
                }
304

305
                $part->setBody($content);
1✔
306
                $part->setContentType($contentType);
1✔
307
                $part->setEncoding(preg_match('#(multipart|message)/#A', $contentType) ? self::Encoding8Bit : self::EncodingBase64);
1✔
308
                $part->setHeader('Content-Disposition', $disposition . '; filename="' . addcslashes($file, '"\\') . '"');
1✔
309
                return $part;
1✔
310
        }
311

312

313
        /********************* building and sending ****************d*g**/
314

315

316
        /**
317
         * Returns encoded message.
318
         */
319
        public function generateMessage(): string
320
        {
321
                return $this->build()->getEncodedMessage();
1✔
322
        }
323

324

325
        /**
326
         * Builds email. Does not modify itself, but returns a new object.
327
         */
328
        public function build(): static
329
        {
330
                $mail = clone $this;
1✔
331
                $mail->setHeader('Message-ID', $mail->getHeader('Message-ID') ?? $this->getRandomId());
1✔
332

333
                $cursor = $mail;
1✔
334
                if ($mail->attachments) {
1✔
335
                        $tmp = $cursor->setContentType('multipart/mixed');
1✔
336
                        $cursor = $cursor->addPart();
1✔
337
                        foreach ($mail->attachments as $value) {
1✔
338
                                $tmp->addPart($value);
1✔
339
                        }
340
                }
341

342
                if ($mail->htmlBody !== '') {
1✔
343
                        $tmp = $cursor->setContentType('multipart/alternative');
1✔
344
                        $cursor = $cursor->addPart();
1✔
345
                        $alt = $tmp->addPart();
1✔
346
                        if ($mail->inlines) {
1✔
347
                                $tmp = $alt->setContentType('multipart/related');
1✔
348
                                $alt = $alt->addPart();
1✔
349
                                foreach ($mail->inlines as $value) {
1✔
350
                                        $tmp->addPart($value);
1✔
351
                                }
352
                        }
353

354
                        $alt->setContentType('text/html', 'UTF-8')
1✔
355
                                ->setEncoding(preg_match('#[^\n]{990}#', $mail->htmlBody)
1✔
356
                                        ? self::EncodingQuotedPrintable
×
357
                                        : (preg_match('#[\x80-\xFF]#', $mail->htmlBody) ? self::Encoding8Bit : self::Encoding7Bit))
1✔
358
                                ->setBody($mail->htmlBody);
1✔
359
                }
360

361
                $text = $mail->getBody();
1✔
362
                $mail->setBody('');
1✔
363
                $cursor->setContentType('text/plain', 'UTF-8')
1✔
364
                        ->setEncoding(preg_match('#[^\n]{990}#', $text)
1✔
365
                                ? self::EncodingQuotedPrintable
1✔
366
                                : (preg_match('#[\x80-\xFF]#', $text) ? self::Encoding8Bit : self::Encoding7Bit))
1✔
367
                        ->setBody($text);
1✔
368

369
                return $mail;
1✔
370
        }
371

372

373
        /**
374
         * Generates a plain-text alternative from HTML.
375
         */
376
        protected function buildText(string $html): string
1✔
377
        {
378
                $html = Strings::replace($html, [
1✔
379
                        '#<(style|script|head).*</\1>#Uis' => '',
1✔
380
                        '#<t[dh][ >]#i' => ' $0',
381
                        '#<a\s[^>]*href=(?|"([^"]+)"|\'([^\']+)\')[^>]*>(.*?)</a>#is' => '$2 &lt;$1&gt;',
382
                        '#[\r\n]+#' => ' ',
383
                        '#<(/?p|/?h\d|li|br|/tr)[ >/]#i' => "\n$0",
384
                ]);
385
                $text = Nette\Utils\Html::htmlToText($html);
1✔
386
                $text = Strings::replace($text, '#[ \t]+#', ' ');
1✔
387
                $text = implode("\n", array_map('trim', explode("\n", $text)));
1✔
388
                return trim($text);
1✔
389
        }
390

391

392
        private function getRandomId(): string
393
        {
394
                return '<' . Nette\Utils\Random::generate() . '@'
1✔
395
                        . preg_replace('#[^\w.-]+#', '', $_SERVER['HTTP_HOST'] ?? php_uname('n'))
1✔
396
                        . '>';
1✔
397
        }
398
}
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