xref: /dokuwiki/inc/Mailer.class.php (revision f90148d34a91c706a0028485431212698fcf8cc6)
1<?php
2/**
3 * A class to build and send multi part mails (with HTML content and embedded
4 * attachments). All mails are assumed to be in UTF-8 encoding.
5 *
6 * Attachments are handled in memory so this shouldn't be used to send huge
7 * files, but then again mail shouldn't be used to send huge files either.
8 *
9 * @author Andreas Gohr <andi@splitbrain.org>
10 */
11use dokuwiki\Utf8\PhpString;
12use dokuwiki\Utf8\Clean;
13use dokuwiki\Extension\Event;
14
15/**
16 * Mail Handling
17 */
18class Mailer {
19
20    protected $headers   = [];
21    protected $attach    = [];
22    protected $html      = '';
23    protected $text      = '';
24
25    protected $boundary  = '';
26    protected $partid    = '';
27    protected $sendparam;
28
29    protected $allowhtml = true;
30
31    protected $replacements = ['text'=> [], 'html' => []];
32
33    /**
34     * Constructor
35     *
36     * Initializes the boundary strings, part counters and token replacements
37     */
38    public function __construct() {
39        global $conf;
40        /* @var Input $INPUT */
41        global $INPUT;
42
43        $server = parse_url(DOKU_URL, PHP_URL_HOST);
44        if(strpos($server,'.') === false) $server .= '.localhost';
45
46        $this->partid   = substr(md5(uniqid(random_int(0, mt_getrandmax()), true)),0, 8).'@'.$server;
47        $this->boundary = '__________'.md5(uniqid(random_int(0, mt_getrandmax()), true));
48
49        $listid = implode('.', array_reverse(explode('/', DOKU_BASE))).$server;
50        $listid = strtolower(trim($listid, '.'));
51
52        $messageid = uniqid(random_int(0, mt_getrandmax()), true) . "@$server";
53
54        $this->allowhtml = (bool)$conf['htmlmail'];
55
56        // add some default headers for mailfiltering FS#2247
57        if(!empty($conf['mailreturnpath'])) {
58            $this->setHeader('Return-Path', $conf['mailreturnpath']);
59        }
60        $this->setHeader('X-Mailer', 'DokuWiki');
61        $this->setHeader('X-DokuWiki-User', $INPUT->server->str('REMOTE_USER'));
62        $this->setHeader('X-DokuWiki-Title', $conf['title']);
63        $this->setHeader('X-DokuWiki-Server', $server);
64        $this->setHeader('X-Auto-Response-Suppress', 'OOF');
65        $this->setHeader('List-Id', $conf['title'].' <'.$listid.'>');
66        $this->setHeader('Date', date('r'), false);
67        $this->setHeader('Message-Id', "<$messageid>");
68
69        $this->prepareTokenReplacements();
70    }
71
72    /**
73     * Attach a file
74     *
75     * @param string $path  Path to the file to attach
76     * @param string $mime  Mimetype of the attached file
77     * @param string $name The filename to use
78     * @param string $embed Unique key to reference this file from the HTML part
79     */
80    public function attachFile($path, $mime, $name = '', $embed = '') {
81        if(!$name) {
82            $name = PhpString::basename($path);
83        }
84
85        $this->attach[] = [
86            'data'  => file_get_contents($path),
87            'mime'  => $mime,
88            'name'  => $name,
89            'embed' => $embed
90        ];
91    }
92
93    /**
94     * Attach a file
95     *
96     * @param string $data  The file contents to attach
97     * @param string $mime  Mimetype of the attached file
98     * @param string $name  The filename to use
99     * @param string $embed Unique key to reference this file from the HTML part
100     */
101    public function attachContent($data, $mime, $name = '', $embed = '') {
102        if(!$name) {
103            [, $ext] = explode('/', $mime);
104            $name = count($this->attach).".$ext";
105        }
106
107        $this->attach[] = [
108            'data'  => $data,
109            'mime'  => $mime,
110            'name'  => $name,
111            'embed' => $embed
112        ];
113    }
114
115    /**
116     * Callback function to automatically embed images referenced in HTML templates
117     *
118     * @param array $matches
119     * @return string placeholder
120     */
121    protected function autoEmbedCallBack($matches) {
122        static $embeds = 0;
123        $embeds++;
124
125        // get file and mime type
126        $media = cleanID($matches[1]);
127        [, $mime] = mimetype($media);
128        $file = mediaFN($media);
129        if(!file_exists($file)) return $matches[0]; //bad reference, keep as is
130
131        // attach it and set placeholder
132        $this->attachFile($file, $mime, '', 'autoembed'.$embeds);
133        return '%%autoembed'.$embeds.'%%';
134    }
135
136    /**
137     * Add an arbitrary header to the mail
138     *
139     * If an empy value is passed, the header is removed
140     *
141     * @param string $header the header name (no trailing colon!)
142     * @param string|string[] $value  the value of the header
143     * @param bool   $clean  remove all non-ASCII chars and line feeds?
144     */
145    public function setHeader($header, $value, $clean = true) {
146        $header = str_replace(' ', '-', ucwords(strtolower(str_replace('-', ' ', $header)))); // streamline casing
147        if($clean) {
148            $header = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@]+/', '', $header);
149            $value  = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@<>]+/', '', $value);
150        }
151
152        // empty value deletes
153        if(is_array($value)){
154            $value = array_map('trim', $value);
155            $value = array_filter($value);
156            if(!$value) $value = '';
157        }else{
158            $value = trim($value);
159        }
160        if($value === '') {
161            if(isset($this->headers[$header])) unset($this->headers[$header]);
162        } else {
163            $this->headers[$header] = $value;
164        }
165    }
166
167    /**
168     * Set additional parameters to be passed to sendmail
169     *
170     * Whatever is set here is directly passed to PHP's mail() command as last
171     * parameter. Depending on the PHP setup this might break mailing alltogether
172     *
173     * @param string $param
174     */
175    public function setParameters($param) {
176        $this->sendparam = $param;
177    }
178
179    /**
180     * Set the text and HTML body and apply replacements
181     *
182     * This function applies a whole bunch of default replacements in addition
183     * to the ones specified as parameters
184     *
185     * If you pass the HTML part or HTML replacements yourself you have to make
186     * sure you encode all HTML special chars correctly
187     *
188     * @param string $text     plain text body
189     * @param array  $textrep  replacements to apply on the text part
190     * @param array  $htmlrep  replacements to apply on the HTML part, null to use $textrep (urls wrapped in <a> tags)
191     * @param string $html     the HTML body, leave null to create it from $text
192     * @param bool   $wrap     wrap the HTML in the default header/Footer
193     */
194    public function setBody($text, $textrep = null, $htmlrep = null, $html = null, $wrap = true) {
195
196        $htmlrep = (array)$htmlrep;
197        $textrep = (array)$textrep;
198
199        // create HTML from text if not given
200        if($html === null) {
201            $html = $text;
202            $html = hsc($html);
203            $html = preg_replace('/^----+$/m', '<hr >', $html);
204            $html = nl2br($html);
205        }
206        if($wrap) {
207            $wrapper = rawLocale('mailwrap', 'html');
208            $html = preg_replace('/\n-- <br \/>.*$/s', '', $html); //strip signature
209            $html = str_replace('@EMAILSIGNATURE@', '', $html); //strip @EMAILSIGNATURE@
210            $html = str_replace('@HTMLBODY@', $html, $wrapper);
211        }
212
213        if(strpos($text, '@EMAILSIGNATURE@') === false) {
214            $text .= '@EMAILSIGNATURE@';
215        }
216
217        // copy over all replacements missing for HTML (autolink URLs)
218        foreach($textrep as $key => $value) {
219            if(isset($htmlrep[$key])) continue;
220            if(media_isexternal($value)) {
221                $htmlrep[$key] = '<a href="'.hsc($value).'">'.hsc($value).'</a>';
222            } else {
223                $htmlrep[$key] = hsc($value);
224            }
225        }
226
227        // embed media from templates
228        $html = preg_replace_callback(
229            '/@MEDIA\(([^\)]+)\)@/',
230            [$this, 'autoEmbedCallBack'], $html
231        );
232
233        // add default token replacements
234        $trep = array_merge($this->replacements['text'], $textrep);
235        $hrep = array_merge($this->replacements['html'], $htmlrep);
236
237        // Apply replacements
238        foreach($trep as $key => $substitution) {
239            $text = str_replace('@'.strtoupper($key).'@', $substitution, $text);
240        }
241        foreach($hrep as $key => $substitution) {
242            $html = str_replace('@'.strtoupper($key).'@', $substitution, $html);
243        }
244
245        $this->setHTML($html);
246        $this->setText($text);
247    }
248
249    /**
250     * Set the HTML part of the mail
251     *
252     * Placeholders can be used to reference embedded attachments
253     *
254     * You probably want to use setBody() instead
255     *
256     * @param string $html
257     */
258    public function setHTML($html) {
259        $this->html = $html;
260    }
261
262    /**
263     * Set the plain text part of the mail
264     *
265     * You probably want to use setBody() instead
266     *
267     * @param string $text
268     */
269    public function setText($text) {
270        $this->text = $text;
271    }
272
273    /**
274     * Add the To: recipients
275     *
276     * @see cleanAddress
277     * @param string|string[]  $address Multiple adresses separated by commas or as array
278     */
279    public function to($address) {
280        $this->setHeader('To', $address, false);
281    }
282
283    /**
284     * Add the Cc: recipients
285     *
286     * @see cleanAddress
287     * @param string|string[]  $address Multiple adresses separated by commas or as array
288     */
289    public function cc($address) {
290        $this->setHeader('Cc', $address, false);
291    }
292
293    /**
294     * Add the Bcc: recipients
295     *
296     * @see cleanAddress
297     * @param string|string[]  $address Multiple adresses separated by commas or as array
298     */
299    public function bcc($address) {
300        $this->setHeader('Bcc', $address, false);
301    }
302
303    /**
304     * Add the From: address
305     *
306     * This is set to $conf['mailfrom'] when not specified so you shouldn't need
307     * to call this function
308     *
309     * @see cleanAddress
310     * @param string  $address from address
311     */
312    public function from($address) {
313        $this->setHeader('From', $address, false);
314    }
315
316    /**
317     * Add the mail's Subject: header
318     *
319     * @param string $subject the mail subject
320     */
321    public function subject($subject) {
322        $this->headers['Subject'] = $subject;
323    }
324
325    /**
326     * Return a clean name which can be safely used in mail address
327     * fields. That means the name will be enclosed in '"' if it includes
328     * a '"' or a ','. Also a '"' will be escaped as '\"'.
329     *
330     * @param string $name the name to clean-up
331     * @see cleanAddress
332     */
333    public function getCleanName($name) {
334        $name = trim($name, " \t\"");
335        $name = str_replace('"', '\"', $name, $count);
336        if ($count > 0 || strpos($name, ',') !== false) {
337            $name = '"'.$name.'"';
338        }
339        return $name;
340    }
341
342    /**
343     * Sets an email address header with correct encoding
344     *
345     * Unicode characters will be deaccented and encoded base64
346     * for headers. Addresses may not contain Non-ASCII data!
347     *
348     * If @$addresses is a string then it will be split into multiple
349     * addresses. Addresses must be separated by a comma. If the display
350     * name includes a comma then it MUST be properly enclosed by '"' to
351     * prevent spliting at the wrong point.
352     *
353     * Example:
354     *   cc("föö <foo@bar.com>, me@somewhere.com","TBcc");
355     *   to("foo, Dr." <foo@bar.com>, me@somewhere.com");
356     *
357     * @param string|string[]  $addresses Multiple adresses separated by commas or as array
358     * @return false|string  the prepared header (can contain multiple lines)
359     */
360    public function cleanAddress($addresses) {
361        $headers = '';
362        if(!is_array($addresses)){
363            $count = preg_match_all('/\s*(?:("[^"]*"[^,]+),*)|([^,]+)\s*,*/', $addresses, $matches, PREG_SET_ORDER);
364            $addresses = [];
365            if ($count !== false && is_array($matches)) {
366                foreach ($matches as $match) {
367                    $addresses[] = rtrim($match[0], ',');
368                }
369            }
370        }
371
372        foreach($addresses as $part) {
373            $part = preg_replace('/[\r\n\0]+/', ' ', $part); // remove attack vectors
374            $part = trim($part);
375
376            // parse address
377            if(preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
378                $text = trim($matches[1]);
379                $addr = $matches[2];
380            } else {
381                $text = '';
382                $addr = $part;
383            }
384            // skip empty ones
385            if(empty($addr)) {
386                continue;
387            }
388
389            // FIXME: is there a way to encode the localpart of a emailaddress?
390            if(!Clean::isASCII($addr)) {
391                msg(hsc("E-Mail address <$addr> is not ASCII"), -1, __LINE__, __FILE__, MSG_ADMINS_ONLY);
392                continue;
393            }
394
395            if(!mail_isvalid($addr)) {
396                msg(hsc("E-Mail address <$addr> is not valid"), -1, __LINE__, __FILE__, MSG_ADMINS_ONLY);
397                continue;
398            }
399
400            // text was given
401            if(!empty($text) && !isWindows()) { // No named recipients for To: in Windows (see FS#652)
402                // add address quotes
403                $addr = "<$addr>";
404
405                if(defined('MAILHEADER_ASCIIONLY')) {
406                    $text = Clean::deaccent($text);
407                    $text = Clean::strip($text);
408                }
409
410                if(strpos($text, ',') !== false || !Clean::isASCII($text)) {
411                    $text = '=?UTF-8?B?'.base64_encode($text).'?=';
412                }
413            } else {
414                $text = '';
415            }
416
417            // add to header comma seperated
418            if($headers != '') {
419                $headers .= ', ';
420            }
421            $headers .= $text.' '.$addr;
422        }
423
424        $headers = trim($headers);
425        if(empty($headers)) return false;
426
427        return $headers;
428    }
429
430
431    /**
432     * Prepare the mime multiparts for all attachments
433     *
434     * Replaces placeholders in the HTML with the correct CIDs
435     *
436     * @return string mime multiparts
437     */
438    protected function prepareAttachments() {
439        $mime = '';
440        $part = 1;
441        // embedded attachments
442        foreach($this->attach as $media) {
443            $media['name'] = str_replace(':', '_', cleanID($media['name'], true));
444
445            // create content id
446            $cid = 'part'.$part.'.'.$this->partid;
447
448            // replace wildcards
449            if($media['embed']) {
450                $this->html = str_replace('%%'.$media['embed'].'%%', 'cid:'.$cid, $this->html);
451            }
452
453            $mime .= '--'.$this->boundary.MAILHEADER_EOL;
454            $mime .= $this->wrappedHeaderLine('Content-Type', $media['mime'].'; id="'.$cid.'"');
455            $mime .= $this->wrappedHeaderLine('Content-Transfer-Encoding', 'base64');
456            $mime .= $this->wrappedHeaderLine('Content-ID',"<$cid>");
457            if($media['embed']) {
458                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'inline; filename='.$media['name']);
459            } else {
460                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'attachment; filename='.$media['name']);
461            }
462            $mime .= MAILHEADER_EOL; //end of headers
463            $mime .= chunk_split(base64_encode($media['data']), 74, MAILHEADER_EOL);
464
465            $part++;
466        }
467        return $mime;
468    }
469
470    /**
471     * Build the body and handles multi part mails
472     *
473     * Needs to be called before prepareHeaders!
474     *
475     * @return string the prepared mail body, false on errors
476     */
477    protected function prepareBody() {
478
479        // no HTML mails allowed? remove HTML body
480        if(!$this->allowhtml) {
481            $this->html = '';
482        }
483
484        // check for body
485        if(!$this->text && !$this->html) {
486            return false;
487        }
488
489        // add general headers
490        $this->headers['MIME-Version'] = '1.0';
491
492        $body = '';
493
494        if(!$this->html && !count($this->attach)) { // we can send a simple single part message
495            $this->headers['Content-Type']              = 'text/plain; charset=UTF-8';
496            $this->headers['Content-Transfer-Encoding'] = 'base64';
497            $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
498        } else { // multi part it is
499            $body .= "This is a multi-part message in MIME format.".MAILHEADER_EOL;
500
501            // prepare the attachments
502            $attachments = $this->prepareAttachments();
503
504            // do we have alternative text content?
505            if($this->text && $this->html) {
506                $this->headers['Content-Type'] = 'multipart/alternative;'.MAILHEADER_EOL.
507                    '  boundary="'.$this->boundary.'XX"';
508                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
509                $body .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL;
510                $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
511                $body .= MAILHEADER_EOL;
512                $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
513                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
514                $body .= 'Content-Type: multipart/related;'.MAILHEADER_EOL.
515                    '  boundary="'.$this->boundary.'";'.MAILHEADER_EOL.
516                    '  type="text/html"'.MAILHEADER_EOL;
517                $body .= MAILHEADER_EOL;
518            }
519
520            $body .= '--'.$this->boundary.MAILHEADER_EOL;
521            $body .= 'Content-Type: text/html; charset=UTF-8'.MAILHEADER_EOL;
522            $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
523            $body .= MAILHEADER_EOL;
524            $body .= chunk_split(base64_encode($this->html), 72, MAILHEADER_EOL);
525            $body .= MAILHEADER_EOL;
526            $body .= $attachments;
527            $body .= '--'.$this->boundary.'--'.MAILHEADER_EOL;
528
529            // close open multipart/alternative boundary
530            if($this->text && $this->html) {
531                $body .= '--'.$this->boundary.'XX--'.MAILHEADER_EOL;
532            }
533        }
534
535        return $body;
536    }
537
538    /**
539     * Cleanup and encode the headers array
540     */
541    protected function cleanHeaders() {
542        global $conf;
543
544        // clean up addresses
545        if(empty($this->headers['From'])) $this->from($conf['mailfrom']);
546        $addrs = ['To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender'];
547        foreach($addrs as $addr) {
548            if(isset($this->headers[$addr])) {
549                $this->headers[$addr] = $this->cleanAddress($this->headers[$addr]);
550            }
551        }
552
553        if(isset($this->headers['Subject'])) {
554            // add prefix to subject
555            if(empty($conf['mailprefix'])) {
556                if(PhpString::strlen($conf['title']) < 20) {
557                    $prefix = '['.$conf['title'].']';
558                } else {
559                    $prefix = '['.PhpString::substr($conf['title'], 0, 20).'...]';
560                }
561            } else {
562                $prefix = '['.$conf['mailprefix'].']';
563            }
564            $len = strlen($prefix);
565            if(substr($this->headers['Subject'], 0, $len) !== $prefix) {
566                $this->headers['Subject'] = $prefix.' '.$this->headers['Subject'];
567            }
568
569            // encode subject
570            if(defined('MAILHEADER_ASCIIONLY')) {
571                $this->headers['Subject'] = Clean::deaccent($this->headers['Subject']);
572                $this->headers['Subject'] = Clean::strip($this->headers['Subject']);
573            }
574            if(!Clean::isASCII($this->headers['Subject'])) {
575                $this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?=';
576            }
577        }
578
579    }
580
581    /**
582     * Returns a complete, EOL terminated header line, wraps it if necessary
583     *
584     * @param string $key
585     * @param string $val
586     * @return string line
587     */
588    protected function wrappedHeaderLine($key, $val){
589        return wordwrap("$key: $val", 78, MAILHEADER_EOL.'  ').MAILHEADER_EOL;
590    }
591
592    /**
593     * Create a string from the headers array
594     *
595     * @returns string the headers
596     */
597    protected function prepareHeaders() {
598        $headers = '';
599        foreach($this->headers as $key => $val) {
600            if ($val === '' || $val === null) continue;
601            $headers .= $this->wrappedHeaderLine($key, $val);
602        }
603        return $headers;
604    }
605
606    /**
607     * return a full email with all headers
608     *
609     * This is mainly intended for debugging and testing but could also be
610     * used for MHT exports
611     *
612     * @return string the mail, false on errors
613     */
614    public function dump() {
615        $this->cleanHeaders();
616        $body = $this->prepareBody();
617        if($body === false) return false;
618        $headers = $this->prepareHeaders();
619
620        return $headers.MAILHEADER_EOL.$body;
621    }
622
623    /**
624     * Prepare default token replacement strings
625     *
626     * Populates the '$replacements' property.
627     * Should be called by the class constructor
628     */
629    protected function prepareTokenReplacements() {
630        global $INFO;
631        global $conf;
632        /* @var Input $INPUT */
633        global $INPUT;
634        global $lang;
635
636        $ip   = clientIP();
637        $cip  = gethostsbyaddrs($ip);
638        $name = $INFO['userinfo']['name'] ?? '';
639        $mail = $INFO['userinfo']['mail'] ?? '';
640
641        $this->replacements['text'] = [
642            'DATE' => dformat(),
643            'BROWSER' => $INPUT->server->str('HTTP_USER_AGENT'),
644            'IPADDRESS' => $ip,
645            'HOSTNAME' => $cip,
646            'TITLE' => $conf['title'],
647            'DOKUWIKIURL' => DOKU_URL,
648            'USER' => $INPUT->server->str('REMOTE_USER'),
649            'NAME' => $name,
650            'MAIL' => $mail
651        ];
652
653        $signature = str_replace(
654            '@DOKUWIKIURL@',
655            $this->replacements['text']['DOKUWIKIURL'],
656            $lang['email_signature_text']
657        );
658        $this->replacements['text']['EMAILSIGNATURE'] = "\n-- \n" . $signature . "\n";
659
660        $this->replacements['html'] = [
661            'DATE' => '<i>' . hsc(dformat()) . '</i>',
662            'BROWSER' => hsc($INPUT->server->str('HTTP_USER_AGENT')),
663            'IPADDRESS' => '<code>' . hsc($ip) . '</code>',
664            'HOSTNAME' => '<code>' . hsc($cip) . '</code>',
665            'TITLE' => hsc($conf['title']),
666            'DOKUWIKIURL' => '<a href="' . DOKU_URL . '">' . DOKU_URL . '</a>',
667            'USER' => hsc($INPUT->server->str('REMOTE_USER')),
668            'NAME' => hsc($name),
669            'MAIL' => '<a href="mailto:"' . hsc($mail) . '">' . hsc($mail) . '</a>'
670        ];
671        $signature = $lang['email_signature_text'];
672        if(!empty($lang['email_signature_html'])) {
673            $signature = $lang['email_signature_html'];
674        }
675        $signature = str_replace(
676            ['@DOKUWIKIURL@', "\n"],
677            [$this->replacements['html']['DOKUWIKIURL'], '<br />'],
678            $signature
679        );
680        $this->replacements['html']['EMAILSIGNATURE'] = $signature;
681    }
682
683    /**
684     * Send the mail
685     *
686     * Call this after all data was set
687     *
688     * @triggers MAIL_MESSAGE_SEND
689     * @return bool true if the mail was successfully passed to the MTA
690     */
691    public function send() {
692        global $lang;
693        $success = false;
694
695        // prepare hook data
696        $data = [
697            // pass the whole mail class to plugin
698            'mail'    => $this,
699            // pass references for backward compatibility
700            'to'      => &$this->headers['To'],
701            'cc'      => &$this->headers['Cc'],
702            'bcc'     => &$this->headers['Bcc'],
703            'from'    => &$this->headers['From'],
704            'subject' => &$this->headers['Subject'],
705            'body'    => &$this->text,
706            'params'  => &$this->sendparam,
707            'headers' => '', // plugins shouldn't use this
708            // signal if we mailed successfully to AFTER event
709            'success' => &$success,
710        ];
711
712        // do our thing if BEFORE hook approves
713        $evt = new Event('MAIL_MESSAGE_SEND', $data);
714        if($evt->advise_before(true)) {
715            // clean up before using the headers
716            $this->cleanHeaders();
717
718            // any recipients?
719            if(trim($this->headers['To']) === '' &&
720                trim($this->headers['Cc']) === '' &&
721                trim($this->headers['Bcc']) === ''
722            ) return false;
723
724            // The To: header is special
725            if(array_key_exists('To', $this->headers)) {
726                $to = (string)$this->headers['To'];
727                unset($this->headers['To']);
728            } else {
729                $to = '';
730            }
731
732            // so is the subject
733            if(array_key_exists('Subject', $this->headers)) {
734                $subject = (string)$this->headers['Subject'];
735                unset($this->headers['Subject']);
736            } else {
737                $subject = '';
738            }
739
740            // make the body
741            $body = $this->prepareBody();
742            if($body === false) return false;
743
744            // cook the headers
745            $headers = $this->prepareHeaders();
746            // add any headers set by legacy plugins
747            if(trim($data['headers'])) {
748                $headers .= MAILHEADER_EOL.trim($data['headers']);
749            }
750
751            if(!function_exists('mail')){
752                $emsg = $lang['email_fail'] . $subject;
753                error_log($emsg);
754                msg(hsc($emsg), -1, __LINE__, __FILE__, MSG_MANAGERS_ONLY);
755                $evt->advise_after();
756                return false;
757            }
758
759            // send the thing
760            if($to === '') $to = '(undisclosed-recipients)'; // #1422
761            if($this->sendparam === null) {
762                $success = @mail($to, $subject, $body, $headers);
763            } else {
764                $success = @mail($to, $subject, $body, $headers, $this->sendparam);
765            }
766        }
767        // any AFTER actions?
768        $evt->advise_after();
769        return $success;
770    }
771}
772