Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationDI
      • ApplicationLatte
      • ApplicationTracy
      • CacheDI
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsDI
      • FormsLatte
      • Framework
      • HttpDI
      • HttpTracy
      • MailDI
      • ReflectionDI
      • SecurityDI
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Conventions
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Utils
  • none
  • Tracy
    • Bridges
      • Nette

Classes

  • Message
  • MimePart
  • SendmailMailer
  • SmtpMailer

Interfaces

  • IMailer

Exceptions

  • SendException
  • SmtpException
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  • Other releases
  • Nette homepage
  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: namespace Nette\Mail;
  9: 
 10: use Nette;
 11: use Nette\Utils\Strings;
 12: 
 13: 
 14: /**
 15:  * Mail provides functionality to compose and send both text and MIME-compliant multipart email messages.
 16:  *
 17:  * @property   string $subject
 18:  * @property   mixed $htmlBody
 19:  */
 20: class Message extends MimePart
 21: {
 22:     /** Priority */
 23:     const HIGH = 1,
 24:         NORMAL = 3,
 25:         LOW = 5;
 26: 
 27:     /** @var array */
 28:     public static $defaultHeaders = array(
 29:         'MIME-Version' => '1.0',
 30:         'X-Mailer' => 'Nette Framework',
 31:     );
 32: 
 33:     /** @var array */
 34:     private $attachments = array();
 35: 
 36:     /** @var array */
 37:     private $inlines = array();
 38: 
 39:     /** @var mixed */
 40:     private $html;
 41: 
 42: 
 43:     public function __construct()
 44:     {
 45:         foreach (static::$defaultHeaders as $name => $value) {
 46:             $this->setHeader($name, $value);
 47:         }
 48:         $this->setHeader('Date', date('r'));
 49:     }
 50: 
 51: 
 52:     /**
 53:      * Sets the sender of the message.
 54:      * @param  string  email or format "John Doe" <doe@example.com>
 55:      * @param  string
 56:      * @return self
 57:      */
 58:     public function setFrom($email, $name = NULL)
 59:     {
 60:         $this->setHeader('From', $this->formatEmail($email, $name));
 61:         return $this;
 62:     }
 63: 
 64: 
 65:     /**
 66:      * Returns the sender of the message.
 67:      * @return array
 68:      */
 69:     public function getFrom()
 70:     {
 71:         return $this->getHeader('From');
 72:     }
 73: 
 74: 
 75:     /**
 76:      * Adds the reply-to address.
 77:      * @param  string  email or format "John Doe" <doe@example.com>
 78:      * @param  string
 79:      * @return self
 80:      */
 81:     public function addReplyTo($email, $name = NULL)
 82:     {
 83:         $this->setHeader('Reply-To', $this->formatEmail($email, $name), TRUE);
 84:         return $this;
 85:     }
 86: 
 87: 
 88:     /**
 89:      * Sets the subject of the message.
 90:      * @param  string
 91:      * @return self
 92:      */
 93:     public function setSubject($subject)
 94:     {
 95:         $this->setHeader('Subject', $subject);
 96:         return $this;
 97:     }
 98: 
 99: 
100:     /**
101:      * Returns the subject of the message.
102:      * @return string
103:      */
104:     public function getSubject()
105:     {
106:         return $this->getHeader('Subject');
107:     }
108: 
109: 
110:     /**
111:      * Adds email recipient.
112:      * @param  string  email or format "John Doe" <doe@example.com>
113:      * @param  string
114:      * @return self
115:      */
116:     public function addTo($email, $name = NULL) // addRecipient()
117:     {
118:         $this->setHeader('To', $this->formatEmail($email, $name), TRUE);
119:         return $this;
120:     }
121: 
122: 
123:     /**
124:      * Adds carbon copy email recipient.
125:      * @param  string  email or format "John Doe" <doe@example.com>
126:      * @param  string
127:      * @return self
128:      */
129:     public function addCc($email, $name = NULL)
130:     {
131:         $this->setHeader('Cc', $this->formatEmail($email, $name), TRUE);
132:         return $this;
133:     }
134: 
135: 
136:     /**
137:      * Adds blind carbon copy email recipient.
138:      * @param  string  email or format "John Doe" <doe@example.com>
139:      * @param  string
140:      * @return self
141:      */
142:     public function addBcc($email, $name = NULL)
143:     {
144:         $this->setHeader('Bcc', $this->formatEmail($email, $name), TRUE);
145:         return $this;
146:     }
147: 
148: 
149:     /**
150:      * Formats recipient email.
151:      * @param  string
152:      * @param  string
153:      * @return array
154:      */
155:     private function formatEmail($email, $name)
156:     {
157:         if (!$name && preg_match('#^(.+) +<(.*)>\z#', $email, $matches)) {
158:             return array($matches[2] => $matches[1]);
159:         } else {
160:             return array($email => $name);
161:         }
162:     }
163: 
164: 
165:     /**
166:      * Sets the Return-Path header of the message.
167:      * @param  string  email
168:      * @return self
169:      */
170:     public function setReturnPath($email)
171:     {
172:         $this->setHeader('Return-Path', $email);
173:         return $this;
174:     }
175: 
176: 
177:     /**
178:      * Returns the Return-Path header.
179:      * @return string
180:      */
181:     public function getReturnPath()
182:     {
183:         return $this->getHeader('Return-Path');
184:     }
185: 
186: 
187:     /**
188:      * Sets email priority.
189:      * @param  int
190:      * @return self
191:      */
192:     public function setPriority($priority)
193:     {
194:         $this->setHeader('X-Priority', (int) $priority);
195:         return $this;
196:     }
197: 
198: 
199:     /**
200:      * Returns email priority.
201:      * @return int
202:      */
203:     public function getPriority()
204:     {
205:         return $this->getHeader('X-Priority');
206:     }
207: 
208: 
209:     /**
210:      * Sets HTML body.
211:      * @param  string
212:      * @param  mixed base-path
213:      * @return self
214:      */
215:     public function setHtmlBody($html, $basePath = NULL)
216:     {
217:         if ($basePath === NULL && ($html instanceof Nette\Templating\IFileTemplate || $html instanceof Nette\Application\UI\ITemplate)) {
218:             $basePath = dirname($html->getFile());
219:             $bc = TRUE;
220:         }
221:         $html = (string) $html;
222: 
223:         if ($basePath) {
224:             $cids = array();
225:             $matches = Strings::matchAll(
226:                 $html,
227:                 '#
228:                     (<img[^<>]*\s src\s*=\s*
229:                     |<body[^<>]*\s background\s*=\s*
230:                     |<[^<>]+\s style\s*=\s* ["\'][^"\'>]+[:\s] url\(
231:                     |<style[^>]*>[^<]+ [:\s] url\()
232:                     (["\']?)(?![a-z]+:|[/\\#])([^"\'>)\s]+)
233:                 #ix',
234:                 PREG_OFFSET_CAPTURE
235:             );
236:             if ($matches && isset($bc)) {
237:                 trigger_error(__METHOD__ . '() missing second argument with image base path.', E_USER_WARNING);
238:             }
239:             foreach (array_reverse($matches) as $m) {
240:                 $file = rtrim($basePath, '/\\') . '/' . urldecode($m[3][0]);
241:                 if (!isset($cids[$file])) {
242:                     $cids[$file] = substr($this->addEmbeddedFile($file)->getHeader('Content-ID'), 1, -1);
243:                 }
244:                 $html = substr_replace($html,
245:                     "{$m[1][0]}{$m[2][0]}cid:{$cids[$file]}",
246:                     $m[0][1], strlen($m[0][0])
247:                 );
248:             }
249:         }
250: 
251:         if ($this->getSubject() == NULL) { // intentionally ==
252:             $html = Strings::replace($html, '#<title>(.+?)</title>#is', function ($m) use (& $title) {
253:                 $title = $m[1];
254:             });
255:             $this->setSubject(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
256:         }
257: 
258:         $this->html = ltrim(str_replace("\r", '', $html), "\n");
259: 
260:         if ($this->getBody() == NULL && $html != NULL) { // intentionally ==
261:             $this->setBody($this->buildText($html));
262:         }
263: 
264:         return $this;
265:     }
266: 
267: 
268:     /**
269:      * Gets HTML body.
270:      * @return mixed
271:      */
272:     public function getHtmlBody()
273:     {
274:         return $this->html;
275:     }
276: 
277: 
278:     /**
279:      * Adds embedded file.
280:      * @param  string
281:      * @param  string
282:      * @param  string
283:      * @return MimePart
284:      */
285:     public function addEmbeddedFile($file, $content = NULL, $contentType = NULL)
286:     {
287:         return $this->inlines[$file] = $this->createAttachment($file, $content, $contentType, 'inline')
288:             ->setHeader('Content-ID', $this->getRandomId());
289:     }
290: 
291: 
292:     /**
293:      * Adds attachment.
294:      * @param  string
295:      * @param  string
296:      * @param  string
297:      * @return MimePart
298:      */
299:     public function addAttachment($file, $content = NULL, $contentType = NULL)
300:     {
301:         return $this->attachments[] = $this->createAttachment($file, $content, $contentType, 'attachment');
302:     }
303: 
304: 
305:     /**
306:      * Gets all email attachments.
307:      * @return MimePart[]
308:      */
309:     public function getAttachments()
310:     {
311:         return $this->attachments;
312:     }
313: 
314: 
315:     /**
316:      * Creates file MIME part.
317:      * @return MimePart
318:      */
319:     private function createAttachment($file, $content, $contentType, $disposition)
320:     {
321:         $part = new MimePart;
322:         if ($content === NULL) {
323:             $content = @file_get_contents($file); // intentionally @
324:             if ($content === FALSE) {
325:                 throw new Nette\FileNotFoundException("Unable to read file '$file'.");
326:             }
327:         } else {
328:             $content = (string) $content;
329:         }
330:         $part->setBody($content);
331:         $part->setContentType($contentType ? $contentType : finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content));
332:         $part->setEncoding(preg_match('#(multipart|message)/#A', $contentType) ? self::ENCODING_8BIT : self::ENCODING_BASE64);
333:         $part->setHeader('Content-Disposition', $disposition . '; filename="' . Strings::fixEncoding(basename($file)) . '"');
334:         return $part;
335:     }
336: 
337: 
338:     /********************* building and sending ****************d*g**/
339: 
340: 
341:     /**
342:      * Returns encoded message.
343:      * @return string
344:      */
345:     public function generateMessage()
346:     {
347:         return $this->build()->getEncodedMessage();
348:     }
349: 
350: 
351:     /**
352:      * Builds email. Does not modify itself, but returns a new object.
353:      * @return self
354:      */
355:     protected function build()
356:     {
357:         $mail = clone $this;
358:         $mail->setHeader('Message-ID', $this->getRandomId());
359: 
360:         $cursor = $mail;
361:         if ($mail->attachments) {
362:             $tmp = $cursor->setContentType('multipart/mixed');
363:             $cursor = $cursor->addPart();
364:             foreach ($mail->attachments as $value) {
365:                 $tmp->addPart($value);
366:             }
367:         }
368: 
369:         if ($mail->html != NULL) { // intentionally ==
370:             $tmp = $cursor->setContentType('multipart/alternative');
371:             $cursor = $cursor->addPart();
372:             $alt = $tmp->addPart();
373:             if ($mail->inlines) {
374:                 $tmp = $alt->setContentType('multipart/related');
375:                 $alt = $alt->addPart();
376:                 foreach ($mail->inlines as $value) {
377:                     $tmp->addPart($value);
378:                 }
379:             }
380:             $alt->setContentType('text/html', 'UTF-8')
381:                 ->setEncoding(preg_match('#[^\n]{990}#', $mail->html)
382:                     ? self::ENCODING_QUOTED_PRINTABLE
383:                     : (preg_match('#[\x80-\xFF]#', $mail->html) ? self::ENCODING_8BIT : self::ENCODING_7BIT))
384:                 ->setBody($mail->html);
385:         }
386: 
387:         $text = $mail->getBody();
388:         $mail->setBody(NULL);
389:         $cursor->setContentType('text/plain', 'UTF-8')
390:             ->setEncoding(preg_match('#[^\n]{990}#', $text)
391:                 ? self::ENCODING_QUOTED_PRINTABLE
392:                 : (preg_match('#[\x80-\xFF]#', $text) ? self::ENCODING_8BIT : self::ENCODING_7BIT))
393:             ->setBody($text);
394: 
395:         return $mail;
396:     }
397: 
398: 
399:     /**
400:      * Builds text content.
401:      * @return string
402:      */
403:     protected function buildText($html)
404:     {
405:         $text = Strings::replace($html, array(
406:             '#<(style|script|head).*</\\1>#Uis' => '',
407:             '#<t[dh][ >]#i' => ' $0',
408:             '#<a [^>]*href=(?|"([^"]+)"|\'([^\']+)\')[^>]*>(.*?)</a>#i' =>  '$2 &lt;$1&gt;',
409:             '#[\r\n]+#' => ' ',
410:             '#<(/?p|/?h\d|li|br|/tr)[ >/]#i' => "\n$0",
411:         ));
412:         $text = html_entity_decode(strip_tags($text), ENT_QUOTES, 'UTF-8');
413:         $text = Strings::replace($text, '#[ \t]+#', ' ');
414:         return trim($text);
415:     }
416: 
417: 
418:     /** @return string */
419:     private function getRandomId()
420:     {
421:         return '<' . Nette\Utils\Random::generate() . '@'
422:             . preg_replace('#[^\w.-]+#', '', isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n'))
423:             . '>';
424:     }
425: 
426: }
427: 
Nette 2.3-20161221 API API documentation generated by ApiGen 2.8.0