2 /*~ class.phpmailer.php
3 .---------------------------------------------------------------------------.
4 | Software: PHPMailer - PHP email class |
6 | Contact: via sourceforge.net support pages (also www.codeworxtech.com) |
7 | Info: http://phpmailer.sourceforge.net |
8 | Support: http://sourceforge.net/projects/phpmailer/ |
9 | ------------------------------------------------------------------------- |
10 | Author: Andy Prevost (project admininistrator) |
11 | Author: Brent R. Matzelle (original founder) |
12 | Copyright (c) 2004-2007, Andy Prevost. All Rights Reserved. |
13 | Copyright (c) 2001-2003, Brent R. Matzelle |
14 | ------------------------------------------------------------------------- |
15 | License: Distributed under the Lesser General Public License (LGPL) |
16 | http://www.gnu.org/copyleft/lesser.html |
17 | This program is distributed in the hope that it will be useful - WITHOUT |
18 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
19 | FITNESS FOR A PARTICULAR PURPOSE. |
20 | ------------------------------------------------------------------------- |
21 | We offer a number of paid services (www.codeworxtech.com): |
22 | - Web Hosting on highly optimized fast and secure servers |
23 | - Technology Consulting |
24 | - Oursourcing (highly qualified programmers and graphic designers) |
25 '---------------------------------------------------------------------------'
28 * PHPMailer - PHP email transport class
30 * @author Andy Prevost
31 * @copyright 2004 - 2007 Andy Prevost
36 /////////////////////////////////////////////////
38 /////////////////////////////////////////////////
41 * Email priority (1 = High, 3 = Normal, 5 = low).
47 * Sets the CharSet of the message.
50 var $CharSet = 'iso-8859-1';
53 * Sets the Content-type of the message.
56 var $ContentType = 'text/plain';
59 * Sets the Encoding of the message. Options for this are "8bit",
60 * "7bit", "binary", "base64", and "quoted-printable".
63 var $Encoding = '8bit';
66 * Holds the most recent mailer error message.
72 * Sets the From email address for the message.
75 var $From = 'root@localhost';
78 * Sets the From name of the message.
81 var $FromName = 'Root User';
84 * Sets the Sender email (Return-Path) of the message. If not empty,
85 * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
91 * Sets the Subject of the message.
97 * Sets the Body of the message. This can be either an HTML or text body.
98 * If HTML then run IsHTML(true).
104 * Sets the text-only body of the message. This automatically sets the
105 * email to multipart/alternative. This body can be read by mail
106 * clients that do not have HTML email capability such as mutt. Clients
107 * that can read HTML will view the normal Body.
113 * Sets word wrapping on the body of the message to a given number of
120 * Method to send mail: ("mail", "sendmail", or "smtp").
123 var $Mailer = 'mail';
126 * Sets the path of the sendmail program.
129 var $Sendmail = '/usr/sbin/sendmail';
132 * Path to PHPMailer plugins. This is now only useful if the SMTP class
133 * is in a different directory than the PHP include path.
139 * Holds PHPMailer version.
142 var $Version = "2.0.0 rc3";
145 * Sets the email address that a reading confirmation will be sent.
148 var $ConfirmReadingTo = '';
151 * Sets the hostname to use in Message-Id and Received headers
152 * and as default HELO string. If empty, the value returned
153 * by SERVER_NAME is used or 'localhost.localdomain'.
158 /////////////////////////////////////////////////
159 // PROPERTIES FOR SMTP
160 /////////////////////////////////////////////////
163 * Sets the SMTP hosts. All hosts must be separated by a
164 * semicolon. You can also specify a different port
165 * for each host by using this format: [hostname:port]
166 * (e.g. "smtp1.example.com:25;smtp2.example.com").
167 * Hosts will be tried in order.
170 var $Host = 'localhost';
173 * Sets the default SMTP server port.
179 * Sets the SMTP HELO of the message (Default is $Hostname).
185 * Sets connection prefix.
186 * Options are "", "ssl" or "tls"
189 var $SMTPSecure = "";
192 * Sets SMTP authentication. Utilizes the Username and Password variables.
195 var $SMTPAuth = false;
198 * Sets SMTP username.
204 * Sets SMTP password.
210 * Sets the SMTP server timeout in seconds. This function will not
211 * work with the win32 version.
217 * Sets SMTP class debugging on or off.
220 var $SMTPDebug = false;
223 * Prevents the SMTP connection from being closed after each mail
224 * sending. If this is set to true then to close the connection
225 * requires an explicit call to SmtpClose().
228 var $SMTPKeepAlive = false;
231 * Provides the ability to have the TO field process individual
232 * emails, instead of sending to entire TO addresses
235 var $SingleTo = false;
237 /////////////////////////////////////////////////
238 // PROPERTIES, PRIVATE
239 /////////////////////////////////////////////////
245 var $ReplyTo = array();
246 var $attachment = array();
247 var $CustomHeader = array();
248 var $message_type = '';
249 var $boundary = array();
250 var $language = array();
251 var $error_count = 0;
254 /////////////////////////////////////////////////
255 // METHODS, VARIABLES
256 /////////////////////////////////////////////////
259 * Sets message type to HTML.
263 function IsHTML($bool) {
265 $this->ContentType = 'text/html';
267 $this->ContentType = 'text/plain';
272 * Sets Mailer to send message using SMTP.
276 $this->Mailer = 'smtp';
280 * Sets Mailer to send message using PHP mail() function.
284 $this->Mailer = 'mail';
288 * Sets Mailer to send message using the $Sendmail program.
291 function IsSendmail() {
292 $this->Mailer = 'sendmail';
296 * Sets Mailer to send message using the qmail MTA.
300 $this->Sendmail = '/var/qmail/bin/sendmail';
301 $this->Mailer = 'sendmail';
304 /////////////////////////////////////////////////
305 // METHODS, RECIPIENTS
306 /////////////////////////////////////////////////
309 * Adds a "To" address.
310 * @param string $address
311 * @param string $name
314 function AddAddress($address, $name = '') {
315 $cur = count($this->to);
316 $this->to[$cur][0] = trim($address);
317 $this->to[$cur][1] = $name;
321 * Adds a "Cc" address. Note: this function works
322 * with the SMTP mailer on win32, not with the "mail"
324 * @param string $address
325 * @param string $name
328 function AddCC($address, $name = '') {
329 $cur = count($this->cc);
330 $this->cc[$cur][0] = trim($address);
331 $this->cc[$cur][1] = $name;
335 * Adds a "Bcc" address. Note: this function works
336 * with the SMTP mailer on win32, not with the "mail"
338 * @param string $address
339 * @param string $name
342 function AddBCC($address, $name = '') {
343 $cur = count($this->bcc);
344 $this->bcc[$cur][0] = trim($address);
345 $this->bcc[$cur][1] = $name;
349 * Adds a "Reply-To" address.
350 * @param string $address
351 * @param string $name
354 function AddReplyTo($address, $name = '') {
355 $cur = count($this->ReplyTo);
356 $this->ReplyTo[$cur][0] = trim($address);
357 $this->ReplyTo[$cur][1] = $name;
360 /////////////////////////////////////////////////
361 // METHODS, MAIL SENDING
362 /////////////////////////////////////////////////
365 * Creates message and assigns Mailer. If the message is
366 * not sent successfully then it returns false. Use the ErrorInfo
367 * variable to view description of the error.
375 if((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
376 $this->SetError($this->Lang('provide_address'));
380 /* Set whether the message is multipart/alternative */
381 if(!empty($this->AltBody)) {
382 $this->ContentType = 'multipart/alternative';
385 $this->error_count = 0; // reset errors
386 $this->SetMessageType();
387 $header .= $this->CreateHeader();
388 $body = $this->CreateBody();
394 /* Choose the mailer */
395 switch($this->Mailer) {
397 $result = $this->SendmailSend($header, $body);
400 $result = $this->SmtpSend($header, $body);
403 $result = $this->MailSend($header, $body);
406 $result = $this->MailSend($header, $body);
408 //$this->SetError($this->Mailer . $this->Lang('mailer_not_supported'));
417 * Sends mail using the $Sendmail program.
421 function SendmailSend($header, $body) {
422 if ($this->Sender != '') {
423 $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
425 $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
428 if(!@$mail = popen($sendmail, 'w')) {
429 $this->SetError($this->Lang('execute') . $this->Sendmail);
433 fputs($mail, $header);
436 $result = pclose($mail) >> 8 & 0xFF;
438 $this->SetError($this->Lang('execute') . $this->Sendmail);
446 * Sends mail using the PHP mail() function.
450 function MailSend($header, $body) {
453 for($i = 0; $i < count($this->to); $i++) {
454 if($i != 0) { $to .= ', '; }
455 $to .= $this->AddrFormat($this->to[$i]);
458 $toArr = split(',', $to);
460 if ($this->Sender != '' && strlen(ini_get('safe_mode'))< 1) {
461 $old_from = ini_get('sendmail_from');
462 ini_set('sendmail_from', $this->Sender);
463 $params = sprintf("-oi -f %s", $this->Sender);
464 if ($this->SingleTo === true && count($toArr) > 1) {
465 foreach ($toArr as $key => $val) {
466 $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
469 $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
472 if ($this->SingleTo === true && count($toArr) > 1) {
473 foreach ($toArr as $key => $val) {
474 $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
477 $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
481 if (isset($old_from)) {
482 ini_set('sendmail_from', $old_from);
486 $this->SetError($this->Lang('instantiate'));
494 * Sends mail via SMTP using PhpSMTP (Author:
495 * Chris Ryan). Returns bool. Returns false if there is a
496 * bad MAIL FROM, RCPT, or DATA input.
500 function SmtpSend($header, $body) {
501 include_once($this->PluginDir . 'class.smtp.php');
505 if(!$this->SmtpConnect()) {
509 $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
510 if(!$this->smtp->Mail($smtp_from)) {
511 $error = $this->Lang('from_failed') . $smtp_from;
512 $this->SetError($error);
513 $this->smtp->Reset();
517 /* Attempt to send attach all recipients */
518 for($i = 0; $i < count($this->to); $i++) {
519 if(!$this->smtp->Recipient($this->to[$i][0])) {
520 $bad_rcpt[] = $this->to[$i][0];
523 for($i = 0; $i < count($this->cc); $i++) {
524 if(!$this->smtp->Recipient($this->cc[$i][0])) {
525 $bad_rcpt[] = $this->cc[$i][0];
528 for($i = 0; $i < count($this->bcc); $i++) {
529 if(!$this->smtp->Recipient($this->bcc[$i][0])) {
530 $bad_rcpt[] = $this->bcc[$i][0];
534 if(count($bad_rcpt) > 0) { // Create error message
535 for($i = 0; $i < count($bad_rcpt); $i++) {
539 $error .= $bad_rcpt[$i];
541 $error = $this->Lang('recipients_failed') . $error;
542 $this->SetError($error);
543 $this->smtp->Reset();
547 if(!$this->smtp->Data($header . $body)) {
548 $this->SetError($this->Lang('data_not_accepted'));
549 $this->smtp->Reset();
552 if($this->SMTPKeepAlive == true) {
553 $this->smtp->Reset();
562 * Initiates a connection to an SMTP server. Returns false if the
567 function SmtpConnect() {
568 if($this->smtp == NULL) {
569 $this->smtp = new SMTP();
572 $this->smtp->do_debug = $this->SMTPDebug;
573 $hosts = explode(';', $this->Host);
575 $connection = ($this->smtp->Connected());
577 /* Retry while there is no connection */
578 while($index < count($hosts) && $connection == false) {
580 if(eregi('^(.+):([0-9]+)$', $hosts[$index], $hostinfo)) {
581 $host = $hostinfo[1];
582 $port = $hostinfo[2];
584 $host = $hosts[$index];
588 if($this->smtp->Connect(((!empty($this->SMTPSecure))?$this->SMTPSecure.'://':'').$host, $port, $this->Timeout)) {
589 if ($this->Helo != '') {
590 $this->smtp->Hello($this->Helo);
592 $this->smtp->Hello($this->ServerHostname());
596 if($this->SMTPAuth) {
597 if(!$this->smtp->Authenticate($this->Username, $this->Password)) {
598 $this->SetError($this->Lang('authenticate'));
599 $this->smtp->Reset();
607 $this->SetError($this->Lang('connect_host'));
614 * Closes the active SMTP session if one exists.
617 function SmtpClose() {
618 if($this->smtp != NULL) {
619 if($this->smtp->Connected()) {
621 $this->smtp->Close();
627 * Sets the language for all class error messages. Returns false
628 * if it cannot load the language file. The default language type
630 * @param string $lang_type Type of language (e.g. Portuguese: "br")
631 * @param string $lang_path Path to the language file directory
635 function SetLanguage($lang_type, $lang_path = 'language/') {
636 if(file_exists($lang_path.'phpmailer.lang-'.$lang_type.'.php')) {
637 include($lang_path.'phpmailer.lang-'.$lang_type.'.php');
638 } elseif (file_exists($lang_path.'phpmailer.lang-en.php')) {
639 include($lang_path.'phpmailer.lang-en.php');
641 $this->SetError('Could not load language file');
644 $this->language = $PHPMAILER_LANG;
649 /////////////////////////////////////////////////
650 // METHODS, MESSAGE CREATION
651 /////////////////////////////////////////////////
654 * Creates recipient headers.
658 function AddrAppend($type, $addr) {
659 $addr_str = $type . ': ';
660 $addr_str .= $this->AddrFormat($addr[0]);
661 if(count($addr) > 1) {
662 for($i = 1; $i < count($addr); $i++) {
663 $addr_str .= ', ' . $this->AddrFormat($addr[$i]);
666 $addr_str .= $this->LE;
672 * Formats an address correctly.
676 function AddrFormat($addr) {
677 if(empty($addr[1])) {
678 $formatted = $this->SecureHeader($addr[0]);
680 $formatted = $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
687 * Wraps message for use with mailers that do not
688 * automatically perform wrapping and for quoted-printable.
689 * Original written by philippe.
693 function WrapText($message, $length, $qp_mode = false) {
694 $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
696 $message = $this->FixEOL($message);
697 if (substr($message, -1) == $this->LE) {
698 $message = substr($message, 0, -1);
701 $line = explode($this->LE, $message);
703 for ($i=0 ;$i < count($line); $i++) {
704 $line_part = explode(' ', $line[$i]);
706 for ($e = 0; $e<count($line_part); $e++) {
707 $word = $line_part[$e];
708 if ($qp_mode and (strlen($word) > $length)) {
709 $space_left = $length - strlen($buf) - 1;
711 if ($space_left > 20) {
713 if (substr($word, $len - 1, 1) == '=') {
715 } elseif (substr($word, $len - 2, 1) == '=') {
718 $part = substr($word, 0, $len);
719 $word = substr($word, $len);
721 $message .= $buf . sprintf("=%s", $this->LE);
723 $message .= $buf . $soft_break;
727 while (strlen($word) > 0) {
729 if (substr($word, $len - 1, 1) == '=') {
731 } elseif (substr($word, $len - 2, 1) == '=') {
734 $part = substr($word, 0, $len);
735 $word = substr($word, $len);
737 if (strlen($word) > 0) {
738 $message .= $part . sprintf("=%s", $this->LE);
745 $buf .= ($e == 0) ? $word : (' ' . $word);
747 if (strlen($buf) > $length and $buf_o != '') {
748 $message .= $buf_o . $soft_break;
753 $message .= $buf . $this->LE;
760 * Set the body wrapping.
764 function SetWordWrap() {
765 if($this->WordWrap < 1) {
769 switch($this->message_type) {
772 case 'alt_attachments':
773 $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
776 $this->Body = $this->WrapText($this->Body, $this->WordWrap);
782 * Assembles message header.
786 function CreateHeader() {
789 /* Set the boundaries */
790 $uniq_id = md5(uniqid(time()));
791 $this->boundary[1] = 'b1_' . $uniq_id;
792 $this->boundary[2] = 'b2_' . $uniq_id;
794 $result .= $this->HeaderLine('Date', $this->RFCDate());
795 if($this->Sender == '') {
796 $result .= $this->HeaderLine('Return-Path', trim($this->From));
798 $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
801 /* To be created automatically by mail() */
802 if($this->Mailer != 'mail') {
803 if(count($this->to) > 0) {
804 $result .= $this->AddrAppend('To', $this->to);
805 } elseif (count($this->cc) == 0) {
806 $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
808 if(count($this->cc) > 0) {
809 $result .= $this->AddrAppend('Cc', $this->cc);
814 $from[0][0] = trim($this->From);
815 $from[0][1] = $this->FromName;
816 $result .= $this->AddrAppend('From', $from);
818 /* sendmail and mail() extract Cc from the header before sending */
819 if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->cc) > 0)) {
820 $result .= $this->AddrAppend('Cc', $this->cc);
823 /* sendmail and mail() extract Bcc from the header before sending */
824 if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
825 $result .= $this->AddrAppend('Bcc', $this->bcc);
828 if(count($this->ReplyTo) > 0) {
829 $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
832 /* mail() sets the subject itself */
833 if($this->Mailer != 'mail') {
834 $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
837 $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
838 $result .= $this->HeaderLine('X-Priority', $this->Priority);
839 $result .= $this->HeaderLine('X-Mailer', 'PHPMailer (phpmailer.sourceforge.net) [version ' . $this->Version . ']');
841 if($this->ConfirmReadingTo != '') {
842 $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
845 // Add custom headers
846 for($index = 0; $index < count($this->CustomHeader); $index++) {
847 $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
849 $result .= $this->HeaderLine('MIME-Version', '1.0');
851 switch($this->message_type) {
853 $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
854 $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
858 case 'alt_attachments':
859 if($this->InlineImageExists()){
860 $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
862 $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
863 $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
867 $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
868 $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
872 if($this->Mailer != 'mail') {
873 $result .= $this->LE.$this->LE;
880 * Assembles the message body. Returns an empty string on failure.
884 function CreateBody() {
887 $this->SetWordWrap();
889 switch($this->message_type) {
891 $result .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
892 $result .= $this->EncodeString($this->AltBody, $this->Encoding);
893 $result .= $this->LE.$this->LE;
894 $result .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
895 $result .= $this->EncodeString($this->Body, $this->Encoding);
896 $result .= $this->LE.$this->LE;
897 $result .= $this->EndBoundary($this->boundary[1]);
900 $result .= $this->EncodeString($this->Body, $this->Encoding);
903 $result .= $this->GetBoundary($this->boundary[1], '', '', '');
904 $result .= $this->EncodeString($this->Body, $this->Encoding);
905 $result .= $this->LE;
906 $result .= $this->AttachAll();
908 case 'alt_attachments':
909 $result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
910 $result .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
911 $result .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
912 $result .= $this->EncodeString($this->AltBody, $this->Encoding);
913 $result .= $this->LE.$this->LE;
914 $result .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
915 $result .= $this->EncodeString($this->Body, $this->Encoding);
916 $result .= $this->LE.$this->LE;
917 $result .= $this->EndBoundary($this->boundary[2]);
918 $result .= $this->AttachAll();
921 if($this->IsError()) {
929 * Returns the start of a message boundary.
932 function GetBoundary($boundary, $charSet, $contentType, $encoding) {
935 $charSet = $this->CharSet;
937 if($contentType == '') {
938 $contentType = $this->ContentType;
940 if($encoding == '') {
941 $encoding = $this->Encoding;
943 $result .= $this->TextLine('--' . $boundary);
944 $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
945 $result .= $this->LE;
946 $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
947 $result .= $this->LE;
953 * Returns the end of a message boundary.
956 function EndBoundary($boundary) {
957 return $this->LE . '--' . $boundary . '--' . $this->LE;
961 * Sets the message type.
965 function SetMessageType() {
966 if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) {
967 $this->message_type = 'plain';
969 if(count($this->attachment) > 0) {
970 $this->message_type = 'attachments';
972 if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) {
973 $this->message_type = 'alt';
975 if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) {
976 $this->message_type = 'alt_attachments';
981 /* Returns a formatted header line.
985 function HeaderLine($name, $value) {
986 return $name . ': ' . $value . $this->LE;
990 * Returns a formatted mail line.
994 function TextLine($value) {
995 return $value . $this->LE;
998 /////////////////////////////////////////////////
999 // CLASS METHODS, ATTACHMENTS
1000 /////////////////////////////////////////////////
1003 * Adds an attachment from a path on the filesystem.
1004 * Returns false if the file could not be found
1006 * @param string $path Path to the attachment.
1007 * @param string $name Overrides the attachment name.
1008 * @param string $encoding File encoding (see $Encoding).
1009 * @param string $type File extension (MIME) type.
1012 function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1013 if(!@is_file($path)) {
1014 $this->SetError($this->Lang('file_access') . $path);
1018 $filename = basename($path);
1023 $cur = count($this->attachment);
1024 $this->attachment[$cur][0] = $path;
1025 $this->attachment[$cur][1] = $filename;
1026 $this->attachment[$cur][2] = $name;
1027 $this->attachment[$cur][3] = $encoding;
1028 $this->attachment[$cur][4] = $type;
1029 $this->attachment[$cur][5] = false; // isStringAttachment
1030 $this->attachment[$cur][6] = 'attachment';
1031 $this->attachment[$cur][7] = 0;
1037 * Attaches all fs, string, and binary attachments to the message.
1038 * Returns an empty string on failure.
1042 function AttachAll() {
1043 /* Return text of body */
1046 /* Add all attachments */
1047 for($i = 0; $i < count($this->attachment); $i++) {
1048 /* Check for string attachment */
1049 $bString = $this->attachment[$i][5];
1051 $string = $this->attachment[$i][0];
1053 $path = $this->attachment[$i][0];
1056 $filename = $this->attachment[$i][1];
1057 $name = $this->attachment[$i][2];
1058 $encoding = $this->attachment[$i][3];
1059 $type = $this->attachment[$i][4];
1060 $disposition = $this->attachment[$i][6];
1061 $cid = $this->attachment[$i][7];
1063 $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
1064 $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE);
1065 $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
1067 if($disposition == 'inline') {
1068 $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1071 $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $name, $this->LE.$this->LE);
1073 /* Encode as string attachment */
1075 $mime[] = $this->EncodeString($string, $encoding);
1076 if($this->IsError()) {
1079 $mime[] = $this->LE.$this->LE;
1081 $mime[] = $this->EncodeFile($path, $encoding);
1082 if($this->IsError()) {
1085 $mime[] = $this->LE.$this->LE;
1089 $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
1091 return join('', $mime);
1095 * Encodes attachment in requested format. Returns an
1096 * empty string on failure.
1100 function EncodeFile ($path, $encoding = 'base64') {
1101 if(!@$fd = fopen($path, 'rb')) {
1102 $this->SetError($this->Lang('file_open') . $path);
1105 $magic_quotes = get_magic_quotes_runtime();
1106 set_magic_quotes_runtime(0);
1107 $file_buffer = fread($fd, filesize($path));
1108 $file_buffer = $this->EncodeString($file_buffer, $encoding);
1110 set_magic_quotes_runtime($magic_quotes);
1112 return $file_buffer;
1116 * Encodes string to requested format. Returns an
1117 * empty string on failure.
1121 function EncodeString ($str, $encoding = 'base64') {
1123 switch(strtolower($encoding)) {
1125 /* chunk_split is found in PHP >= 3.0.6 */
1126 $encoded = chunk_split(base64_encode($str), 76, $this->LE);
1130 $encoded = $this->FixEOL($str);
1131 if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1132 $encoded .= $this->LE;
1137 case 'quoted-printable':
1138 $encoded = $this->EncodeQP($str);
1141 $this->SetError($this->Lang('encoding') . $encoding);
1148 * Encode a header string to best of Q, B, quoted or none.
1152 function EncodeHeader ($str, $position = 'text') {
1155 switch (strtolower($position)) {
1157 if (!preg_match('/[\200-\377]/', $str)) {
1158 /* Can't use addslashes as we don't know what value has magic_quotes_sybase. */
1159 $encoded = addcslashes($str, "\0..\37\177\\\"");
1160 if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
1163 return ("\"$encoded\"");
1166 $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1169 $x = preg_match_all('/[()"]/', $str, $matches);
1173 $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1181 $maxlen = 75 - 7 - strlen($this->CharSet);
1182 /* Try to select the encoding which should produce the shortest output */
1183 if (strlen($str)/3 < $x) {
1185 $encoded = base64_encode($str);
1186 $maxlen -= $maxlen % 4;
1187 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1190 $encoded = $this->EncodeQ($str, $position);
1191 $encoded = $this->WrapText($encoded, $maxlen, true);
1192 $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
1195 $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
1196 $encoded = trim(str_replace("\n", $this->LE, $encoded));
1202 * Encode string to quoted-printable.
1206 function EncodeQP( $input = '', $line_max = 76, $space_conv = false ) {
1207 $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
1208 $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
1212 while( list(, $line) = each($lines) ) {
1213 $linlen = strlen($line);
1215 for($i = 0; $i < $linlen; $i++) {
1216 $c = substr( $line, $i, 1 );
1218 if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
1222 if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
1224 } else if ( $space_conv ) {
1227 } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
1228 $h2 = floor($dec/16);
1229 $h1 = floor($dec%16);
1230 $c = $escape.$hex[$h2].$hex[$h1];
1232 if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
1233 $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
1235 // check if newline first character will be point or not
1242 $output .= $newline.$eol;
1244 return trim($output);
1248 * Encode string to q encoding.
1252 function EncodeQ ($str, $position = 'text') {
1253 /* There should not be any EOL in the string */
1254 $encoded = preg_replace("[\r\n]", '', $str);
1256 switch (strtolower($position)) {
1258 $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1261 $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
1264 /* Replace every high ascii, control =, ? and _ characters */
1265 $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
1266 "'='.sprintf('%02X', ord('\\1'))", $encoded);
1270 /* Replace every spaces to _ (more readable than =20) */
1271 $encoded = str_replace(' ', '_', $encoded);
1277 * Adds a string or binary attachment (non-filesystem) to the list.
1278 * This method can be used to attach ascii or binary data,
1279 * such as a BLOB record from a database.
1280 * @param string $string String attachment data.
1281 * @param string $filename Name of the attachment.
1282 * @param string $encoding File encoding (see $Encoding).
1283 * @param string $type File extension (MIME) type.
1286 function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
1287 /* Append to $attachment array */
1288 $cur = count($this->attachment);
1289 $this->attachment[$cur][0] = $string;
1290 $this->attachment[$cur][1] = $filename;
1291 $this->attachment[$cur][2] = $filename;
1292 $this->attachment[$cur][3] = $encoding;
1293 $this->attachment[$cur][4] = $type;
1294 $this->attachment[$cur][5] = true; // isString
1295 $this->attachment[$cur][6] = 'attachment';
1296 $this->attachment[$cur][7] = 0;
1300 * Adds an embedded attachment. This can include images, sounds, and
1301 * just about any other document. Make sure to set the $type to an
1302 * image type. For JPEG images use "image/jpeg" and for GIF images
1304 * @param string $path Path to the attachment.
1305 * @param string $cid Content ID of the attachment. Use this to identify
1306 * the Id for accessing the image in an HTML form.
1307 * @param string $name Overrides the attachment name.
1308 * @param string $encoding File encoding (see $Encoding).
1309 * @param string $type File extension (MIME) type.
1312 function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1314 if(!@is_file($path)) {
1315 $this->SetError($this->Lang('file_access') . $path);
1319 $filename = basename($path);
1324 /* Append to $attachment array */
1325 $cur = count($this->attachment);
1326 $this->attachment[$cur][0] = $path;
1327 $this->attachment[$cur][1] = $filename;
1328 $this->attachment[$cur][2] = $name;
1329 $this->attachment[$cur][3] = $encoding;
1330 $this->attachment[$cur][4] = $type;
1331 $this->attachment[$cur][5] = false;
1332 $this->attachment[$cur][6] = 'inline';
1333 $this->attachment[$cur][7] = $cid;
1339 * Returns true if an inline attachment is present.
1343 function InlineImageExists() {
1345 for($i = 0; $i < count($this->attachment); $i++) {
1346 if($this->attachment[$i][6] == 'inline') {
1355 /////////////////////////////////////////////////
1356 // CLASS METHODS, MESSAGE RESET
1357 /////////////////////////////////////////////////
1360 * Clears all recipients assigned in the TO array. Returns void.
1363 function ClearAddresses() {
1364 $this->to = array();
1368 * Clears all recipients assigned in the CC array. Returns void.
1371 function ClearCCs() {
1372 $this->cc = array();
1376 * Clears all recipients assigned in the BCC array. Returns void.
1379 function ClearBCCs() {
1380 $this->bcc = array();
1384 * Clears all recipients assigned in the ReplyTo array. Returns void.
1387 function ClearReplyTos() {
1388 $this->ReplyTo = array();
1392 * Clears all recipients assigned in the TO, CC and BCC
1393 * array. Returns void.
1396 function ClearAllRecipients() {
1397 $this->to = array();
1398 $this->cc = array();
1399 $this->bcc = array();
1403 * Clears all previously set filesystem, string, and binary
1404 * attachments. Returns void.
1407 function ClearAttachments() {
1408 $this->attachment = array();
1412 * Clears all custom headers. Returns void.
1415 function ClearCustomHeaders() {
1416 $this->CustomHeader = array();
1419 /////////////////////////////////////////////////
1420 // CLASS METHODS, MISCELLANEOUS
1421 /////////////////////////////////////////////////
1424 * Adds the error message to the error container.
1429 function SetError($msg) {
1430 $this->error_count++;
1431 $this->ErrorInfo = $msg;
1435 * Returns the proper RFC 822 formatted date.
1439 function RFCDate() {
1441 $tzs = ($tz < 0) ? '-' : '+';
1443 $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
1444 $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
1450 * Returns the appropriate server variable. Should work with both
1451 * PHP 4.1.0+ as well as older versions. Returns an empty string
1452 * if nothing is found.
1456 function ServerVar($varName) {
1457 global $HTTP_SERVER_VARS;
1458 global $HTTP_ENV_VARS;
1460 if(!isset($_SERVER)) {
1461 $_SERVER = $HTTP_SERVER_VARS;
1462 if(!isset($_SERVER['REMOTE_ADDR'])) {
1463 $_SERVER = $HTTP_ENV_VARS; // must be Apache
1467 if(isset($_SERVER[$varName])) {
1468 return $_SERVER[$varName];
1475 * Returns the server hostname or 'localhost.localdomain' if unknown.
1479 function ServerHostname() {
1480 if ($this->Hostname != '') {
1481 $result = $this->Hostname;
1482 } elseif ($this->ServerVar('SERVER_NAME') != '') {
1483 $result = $this->ServerVar('SERVER_NAME');
1485 $result = 'localhost.localdomain';
1492 * Returns a message in the appropriate language.
1496 function Lang($key) {
1497 if(count($this->language) < 1) {
1498 $this->SetLanguage('en'); // set the default language
1501 if(isset($this->language[$key])) {
1502 return $this->language[$key];
1504 return 'Language string failed to load: ' . $key;
1509 * Returns true if an error occurred.
1512 function IsError() {
1513 return ($this->error_count > 0);
1517 * Changes every end of line from CR or LF to CRLF.
1521 function FixEOL($str) {
1522 $str = str_replace("\r\n", "\n", $str);
1523 $str = str_replace("\r", "\n", $str);
1524 $str = str_replace("\n", $this->LE, $str);
1529 * Adds a custom header.
1532 function AddCustomHeader($custom_header) {
1533 $this->CustomHeader[] = explode(':', $custom_header, 2);
1537 * Evaluates the message and returns modifications for inline images and backgrounds
1541 function MsgHTML($message) {
1542 preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
1543 if(isset($images[2])) {
1544 foreach($images[2] as $i => $url) {
1545 $filename = basename($url);
1546 $directory = dirname($url);
1547 $cid = 'cid:' . md5($filename);
1548 $fileParts = split("\.", $filename);
1549 $ext = $fileParts[1];
1550 $mimeType = $this->_mime_types($ext);
1551 $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
1552 $this->AddEmbeddedImage($url, md5($filename), $filename, 'base64', $mimeType);
1555 $this->IsHTML(true);
1556 $this->Body = $message;
1557 $textMsg = trim(strip_tags($message));
1558 if ( !empty($textMsg) && empty($this->AltBody) ) {
1559 $this->AltBody = $textMsg;
1561 if ( empty($this->AltBody) ) {
1562 $this->AltBody = 'To view this email message, open the email in with HTML compatibility!' . "\n\n";
1567 * Gets the mime type of the embedded or inline image
1569 * @return mime type of ext
1571 function _mime_types($ext = '') {
1573 'hqx' => 'application/mac-binhex40',
1574 'cpt' => 'application/mac-compactpro',
1575 'doc' => 'application/msword',
1576 'bin' => 'application/macbinary',
1577 'dms' => 'application/octet-stream',
1578 'lha' => 'application/octet-stream',
1579 'lzh' => 'application/octet-stream',
1580 'exe' => 'application/octet-stream',
1581 'class' => 'application/octet-stream',
1582 'psd' => 'application/octet-stream',
1583 'so' => 'application/octet-stream',
1584 'sea' => 'application/octet-stream',
1585 'dll' => 'application/octet-stream',
1586 'oda' => 'application/oda',
1587 'pdf' => 'application/pdf',
1588 'ai' => 'application/postscript',
1589 'eps' => 'application/postscript',
1590 'ps' => 'application/postscript',
1591 'smi' => 'application/smil',
1592 'smil' => 'application/smil',
1593 'mif' => 'application/vnd.mif',
1594 'xls' => 'application/vnd.ms-excel',
1595 'ppt' => 'application/vnd.ms-powerpoint',
1596 'wbxml' => 'application/vnd.wap.wbxml',
1597 'wmlc' => 'application/vnd.wap.wmlc',
1598 'dcr' => 'application/x-director',
1599 'dir' => 'application/x-director',
1600 'dxr' => 'application/x-director',
1601 'dvi' => 'application/x-dvi',
1602 'gtar' => 'application/x-gtar',
1603 'php' => 'application/x-httpd-php',
1604 'php4' => 'application/x-httpd-php',
1605 'php3' => 'application/x-httpd-php',
1606 'phtml' => 'application/x-httpd-php',
1607 'phps' => 'application/x-httpd-php-source',
1608 'js' => 'application/x-javascript',
1609 'swf' => 'application/x-shockwave-flash',
1610 'sit' => 'application/x-stuffit',
1611 'tar' => 'application/x-tar',
1612 'tgz' => 'application/x-tar',
1613 'xhtml' => 'application/xhtml+xml',
1614 'xht' => 'application/xhtml+xml',
1615 'zip' => 'application/zip',
1616 'mid' => 'audio/midi',
1617 'midi' => 'audio/midi',
1618 'mpga' => 'audio/mpeg',
1619 'mp2' => 'audio/mpeg',
1620 'mp3' => 'audio/mpeg',
1621 'aif' => 'audio/x-aiff',
1622 'aiff' => 'audio/x-aiff',
1623 'aifc' => 'audio/x-aiff',
1624 'ram' => 'audio/x-pn-realaudio',
1625 'rm' => 'audio/x-pn-realaudio',
1626 'rpm' => 'audio/x-pn-realaudio-plugin',
1627 'ra' => 'audio/x-realaudio',
1628 'rv' => 'video/vnd.rn-realvideo',
1629 'wav' => 'audio/x-wav',
1630 'bmp' => 'image/bmp',
1631 'gif' => 'image/gif',
1632 'jpeg' => 'image/jpeg',
1633 'jpg' => 'image/jpeg',
1634 'jpe' => 'image/jpeg',
1635 'png' => 'image/png',
1636 'tiff' => 'image/tiff',
1637 'tif' => 'image/tiff',
1638 'css' => 'text/css',
1639 'html' => 'text/html',
1640 'htm' => 'text/html',
1641 'shtml' => 'text/html',
1642 'txt' => 'text/plain',
1643 'text' => 'text/plain',
1644 'log' => 'text/plain',
1645 'rtx' => 'text/richtext',
1646 'rtf' => 'text/rtf',
1647 'xml' => 'text/xml',
1648 'xsl' => 'text/xml',
1649 'mpeg' => 'video/mpeg',
1650 'mpg' => 'video/mpeg',
1651 'mpe' => 'video/mpeg',
1652 'qt' => 'video/quicktime',
1653 'mov' => 'video/quicktime',
1654 'avi' => 'video/x-msvideo',
1655 'movie' => 'video/x-sgi-movie',
1656 'doc' => 'application/msword',
1657 'word' => 'application/msword',
1658 'xl' => 'application/excel',
1659 'eml' => 'message/rfc822'
1661 return ( ! isset($mimes[strtolower($ext)])) ? 'application/x-unknown-content-type' : $mimes[strtolower($ext)];
1665 * Set (or reset) Class Objects (variables)
1668 * $page->set('X-Priority', '3');
1671 * @param string $name Parameter Name
1672 * @param mixed $value Parameter Value
1673 * NOTE: will not work with arrays, there are no arrays to set/reset
1675 function set ( $name, $value = '' ) {
1676 if ( isset($this->$name) ) {
1677 $this->$name = $value;
1679 $this->SetError('Cannot set or reset variable ' . $name);
1685 * Read a file from a supplied filename and return it.
1688 * @param string $filename Parameter File Name
1690 function getFile($filename) {
1692 if ($fp = fopen($filename, 'rb')) {
1693 while (!feof($fp)) {
1694 $return .= fread($fp, 1024);
1704 * Strips newlines to prevent header injection.
1706 * @param string $str String
1709 function SecureHeader($str) {
1711 $str = str_replace("\r", "", $str);
1712 $str = str_replace("\n", "", $str);