1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 4.3.2 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2009, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
19 * CodeIgniter Email Class
21 * Permits email to be sent using Mail, Sendmail, or SMTP.
23 * @package CodeIgniter
24 * @subpackage Libraries
26 * @author ExpressionEngine Dev Team
27 * @link http://codeigniter.com/user_guide/libraries/email.html
31 var $useragent = "CodeIgniter";
32 var $mailpath = "/usr/sbin/sendmail"; // Sendmail path
33 var $protocol = "mail"; // mail/sendmail/smtp
34 var $smtp_host = ""; // SMTP Server. Example: mail.earthlink.net
35 var $smtp_user = ""; // SMTP Username
36 var $smtp_pass = ""; // SMTP Password
37 var $smtp_port = "25"; // SMTP Port
38 var $smtp_timeout = 5; // SMTP Timeout in seconds
39 var $wordwrap = TRUE; // TRUE/FALSE Turns word-wrap on/off
40 var $wrapchars = "76"; // Number of characters to wrap at.
41 var $mailtype = "text"; // text/html Defines email formatting
42 var $charset = "utf-8"; // Default char set: iso-8859-1 or us-ascii
43 var $multipart = "mixed"; // "mixed" (in the body) or "related" (separate)
44 var $alt_message = ''; // Alternative message for HTML emails
45 var $validate = FALSE; // TRUE/FALSE. Enables email validation
46 var $priority = "3"; // Default priority (1 - 5)
47 var $newline = "\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)
48 var $crlf = "\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers,
49 // even on the receiving end think they need to muck with CRLFs, so using "\n", while
50 // distasteful, is the only thing that seems to work for all environments.
51 var $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo.
52 var $bcc_batch_mode = FALSE; // TRUE/FALSE Turns on/off Bcc batch feature
53 var $bcc_batch_size = 200; // If bcc_batch_mode = TRUE, sets max number of Bccs in each batch
54 var $_safe_mode = FALSE;
58 var $_alt_boundary = "";
59 var $_atc_boundary = "";
60 var $_header_str = "";
61 var $_smtp_connect = "";
62 var $_encoding = "8bit";
64 var $_smtp_auth = FALSE;
65 var $_replyto_flag = FALSE;
66 var $_debug_msg = array();
67 var $_recipients = array();
68 var $_cc_array = array();
69 var $_bcc_array = array();
70 var $_headers = array();
71 var $_attach_name = array();
72 var $_attach_type = array();
73 var $_attach_disp = array();
74 var $_protocols = array('mail', 'sendmail', 'smtp');
75 var $_base_charsets = array('us-ascii', 'iso-2022-'); // 7-bit charsets (excluding language suffix)
76 var $_bit_depths = array('7bit', '8bit');
77 var $_priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
81 * Constructor - Sets Email Preferences
83 * The constructor can be passed an array of config values
85 function CI_Email($config = array())
87 if (count($config) > 0)
89 $this->initialize($config);
93 $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
94 $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
97 log_message('debug', "Email Class Initialized");
100 // --------------------------------------------------------------------
103 * Initialize preferences
109 function initialize($config = array())
112 foreach ($config as $key => $val)
114 if (isset($this->$key))
116 $method = 'set_'.$key;
118 if (method_exists($this, $method))
120 $this->$method($val);
129 $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
130 $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
133 // --------------------------------------------------------------------
136 * Initialize the Email Data
141 function clear($clear_attachments = FALSE)
143 $this->_subject = "";
145 $this->_finalbody = "";
146 $this->_header_str = "";
147 $this->_replyto_flag = FALSE;
148 $this->_recipients = array();
149 $this->_headers = array();
150 $this->_debug_msg = array();
152 $this->_set_header('User-Agent', $this->useragent);
153 $this->_set_header('Date', $this->_set_date());
155 if ($clear_attachments !== FALSE)
157 $this->_attach_name = array();
158 $this->_attach_type = array();
159 $this->_attach_disp = array();
163 // --------------------------------------------------------------------
173 function from($from, $name = '')
175 if (preg_match( '/\<(.*)\>/', $from, $match))
182 $this->validate_email($this->_str_to_array($from));
185 // prepare the display name
188 // only use Q encoding if there are characters that would require it
189 if ( ! preg_match('/[\200-\377]/', $name))
191 // add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
192 $name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
196 $name = $this->_prep_q_encoding($name, TRUE);
200 $this->_set_header('From', $name.' <'.$from.'>');
201 $this->_set_header('Return-Path', '<'.$from.'>');
204 // --------------------------------------------------------------------
214 function reply_to($replyto, $name = '')
216 if (preg_match( '/\<(.*)\>/', $replyto, $match))
218 $replyto = $match['1'];
223 $this->validate_email($this->_str_to_array($replyto));
231 if (strncmp($name, '"', 1) != 0)
233 $name = '"'.$name.'"';
236 $this->_set_header('Reply-To', $name.' <'.$replyto.'>');
237 $this->_replyto_flag = TRUE;
240 // --------------------------------------------------------------------
251 $to = $this->_str_to_array($to);
252 $to = $this->clean_email($to);
256 $this->validate_email($to);
259 if ($this->_get_protocol() != 'mail')
261 $this->_set_header('To', implode(", ", $to));
264 switch ($this->_get_protocol())
266 case 'smtp' : $this->_recipients = $to;
268 case 'sendmail' : $this->_recipients = implode(", ", $to);
270 case 'mail' : $this->_recipients = implode(", ", $to);
275 // --------------------------------------------------------------------
286 $cc = $this->_str_to_array($cc);
287 $cc = $this->clean_email($cc);
291 $this->validate_email($cc);
294 $this->_set_header('Cc', implode(", ", $cc));
296 if ($this->_get_protocol() == "smtp")
298 $this->_cc_array = $cc;
302 // --------------------------------------------------------------------
312 function bcc($bcc, $limit = '')
314 if ($limit != '' && is_numeric($limit))
316 $this->bcc_batch_mode = TRUE;
317 $this->bcc_batch_size = $limit;
320 $bcc = $this->_str_to_array($bcc);
321 $bcc = $this->clean_email($bcc);
325 $this->validate_email($bcc);
328 if (($this->_get_protocol() == "smtp") OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
330 $this->_bcc_array = $bcc;
334 $this->_set_header('Bcc', implode(", ", $bcc));
338 // --------------------------------------------------------------------
347 function subject($subject)
349 $subject = $this->_prep_q_encoding($subject);
350 $this->_set_header('Subject', $subject);
353 // --------------------------------------------------------------------
362 function message($body)
364 $this->_body = stripslashes(rtrim(str_replace("\r", "", $body)));
367 // --------------------------------------------------------------------
370 * Assign file attachments
376 function attach($filename, $disposition = 'attachment')
378 $this->_attach_name[] = $filename;
379 $this->_attach_type[] = $this->_mime_types(next(explode('.', basename($filename))));
380 $this->_attach_disp[] = $disposition; // Can also be 'inline' Not sure if it matters
383 // --------------------------------------------------------------------
393 function _set_header($header, $value)
395 $this->_headers[$header] = $value;
398 // --------------------------------------------------------------------
401 * Convert a String to an Array
407 function _str_to_array($email)
409 if ( ! is_array($email))
411 if (strpos($email, ',') !== FALSE)
413 $email = preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY);
417 $email = trim($email);
418 settype($email, "array");
424 // --------------------------------------------------------------------
427 * Set Multipart Value
433 function set_alt_message($str = '')
435 $this->alt_message = ($str == '') ? '' : $str;
438 // --------------------------------------------------------------------
447 function set_mailtype($type = 'text')
449 $this->mailtype = ($type == 'html') ? 'html' : 'text';
452 // --------------------------------------------------------------------
461 function set_wordwrap($wordwrap = TRUE)
463 $this->wordwrap = ($wordwrap === FALSE) ? FALSE : TRUE;
466 // --------------------------------------------------------------------
475 function set_protocol($protocol = 'mail')
477 $this->protocol = ( ! in_array($protocol, $this->_protocols, TRUE)) ? 'mail' : strtolower($protocol);
480 // --------------------------------------------------------------------
489 function set_priority($n = 3)
491 if ( ! is_numeric($n))
497 if ($n < 1 OR $n > 5)
503 $this->priority = $n;
506 // --------------------------------------------------------------------
509 * Set Newline Character
515 function set_newline($newline = "\n")
517 if ($newline != "\n" AND $newline != "\r\n" AND $newline != "\r")
519 $this->newline = "\n";
523 $this->newline = $newline;
526 // --------------------------------------------------------------------
535 function set_crlf($crlf = "\n")
537 if ($crlf != "\n" AND $crlf != "\r\n" AND $crlf != "\r")
546 // --------------------------------------------------------------------
549 * Set Message Boundary
554 function _set_boundaries()
556 $this->_alt_boundary = "B_ALT_".uniqid(''); // multipart/alternative
557 $this->_atc_boundary = "B_ATC_".uniqid(''); // attachment boundary
560 // --------------------------------------------------------------------
568 function _get_message_id()
570 $from = $this->_headers['Return-Path'];
571 $from = str_replace(">", "", $from);
572 $from = str_replace("<", "", $from);
574 return "<".uniqid('').strstr($from, '@').">";
577 // --------------------------------------------------------------------
586 function _get_protocol($return = TRUE)
588 $this->protocol = strtolower($this->protocol);
589 $this->protocol = ( ! in_array($this->protocol, $this->_protocols, TRUE)) ? 'mail' : $this->protocol;
593 return $this->protocol;
597 // --------------------------------------------------------------------
606 function _get_encoding($return = TRUE)
608 $this->_encoding = ( ! in_array($this->_encoding, $this->_bit_depths)) ? '8bit' : $this->_encoding;
610 foreach ($this->_base_charsets as $charset)
612 if (strncmp($charset, $this->charset, strlen($charset)) == 0)
614 $this->_encoding = '7bit';
620 return $this->_encoding;
624 // --------------------------------------------------------------------
627 * Get content type (text/html/attachment)
632 function _get_content_type()
634 if ($this->mailtype == 'html' && count($this->_attach_name) == 0)
638 elseif ($this->mailtype == 'html' && count($this->_attach_name) > 0)
640 return 'html-attach';
642 elseif ($this->mailtype == 'text' && count($this->_attach_name) > 0)
644 return 'plain-attach';
652 // --------------------------------------------------------------------
662 $timezone = date("Z");
663 $operator = (strncmp($timezone, '-', 1) == 0) ? '-' : '+';
664 $timezone = abs($timezone);
665 $timezone = floor($timezone/3600) * 100 + ($timezone % 3600 ) / 60;
667 return sprintf("%s %s%04d", date("D, j M Y H:i:s"), $operator, $timezone);
670 // --------------------------------------------------------------------
678 function _get_mime_message()
680 return "This is a multi-part message in MIME format.".$this->newline."Your email application may not support this format.";
683 // --------------------------------------------------------------------
686 * Validate Email Address
692 function validate_email($email)
694 if ( ! is_array($email))
696 $this->_set_error_message('email_must_be_array');
700 foreach ($email as $val)
702 if ( ! $this->valid_email($val))
704 $this->_set_error_message('email_invalid_address', $val);
712 // --------------------------------------------------------------------
721 function valid_email($address)
723 return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
726 // --------------------------------------------------------------------
729 * Clean Extended Email Address: Joe Smith <joe@smith.com>
735 function clean_email($email)
737 if ( ! is_array($email))
739 if (preg_match('/\<(.*)\>/', $email, $match))
749 $clean_email = array();
751 foreach ($email as $addy)
753 if (preg_match( '/\<(.*)\>/', $addy, $match))
755 $clean_email[] = $match['1'];
759 $clean_email[] = $addy;
766 // --------------------------------------------------------------------
769 * Build alternative plain text message
771 * This function provides the raw message for use
772 * in plain-text headers of HTML-formatted emails.
773 * If the user hasn't specified his own alternative message
774 * it creates one by stripping the HTML
779 function _get_alt_message()
781 if ($this->alt_message != "")
783 return $this->word_wrap($this->alt_message, '76');
786 if (preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match))
792 $body = $this->_body;
795 $body = trim(strip_tags($body));
796 $body = preg_replace( '#<!--(.*)--\>#', "", $body);
797 $body = str_replace("\t", "", $body);
799 for ($i = 20; $i >= 3; $i--)
803 for ($x = 1; $x <= $i; $x ++)
808 $body = str_replace($n, "\n\n", $body);
811 return $this->word_wrap($body, '76');
814 // --------------------------------------------------------------------
824 function word_wrap($str, $charlim = '')
826 // Se the character limit
829 $charlim = ($this->wrapchars == "") ? "76" : $this->wrapchars;
832 // Reduce multiple spaces
833 $str = preg_replace("| +|", " ", $str);
835 // Standardize newlines
836 if (strpos($str, "\r") !== FALSE)
838 $str = str_replace(array("\r\n", "\r"), "\n", $str);
841 // If the current word is surrounded by {unwrap} tags we'll
842 // strip the entire chunk and replace it with a marker.
844 if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches))
846 for ($i = 0; $i < count($matches['0']); $i++)
848 $unwrap[] = $matches['1'][$i];
849 $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str);
853 // Use PHP's native function to do the initial wordwrap.
854 // We set the cut flag to FALSE so that any individual words that are
855 // too long get left alone. In the next step we'll deal with them.
856 $str = wordwrap($str, $charlim, "\n", FALSE);
858 // Split the string into individual lines of text and cycle through them
860 foreach (explode("\n", $str) as $line)
862 // Is the line within the allowed character count?
863 // If so we'll join it to the output and continue
864 if (strlen($line) <= $charlim)
866 $output .= $line.$this->newline;
871 while((strlen($line)) > $charlim)
873 // If the over-length word is a URL we won't wrap it
874 if (preg_match("!\[url.+\]|://|wwww.!", $line))
879 // Trim the word down
880 $temp .= substr($line, 0, $charlim-1);
881 $line = substr($line, $charlim-1);
884 // If $temp contains data it means we had to split up an over-length
885 // word into smaller chunks so we'll add it back to our current line
888 $output .= $temp.$this->newline.$line;
895 $output .= $this->newline;
898 // Put our markers back
899 if (count($unwrap) > 0)
901 foreach ($unwrap as $key => $val)
903 $output = str_replace("{{unwrapped".$key."}}", $val, $output);
910 // --------------------------------------------------------------------
913 * Build final headers
919 function _build_headers()
921 $this->_set_header('X-Sender', $this->clean_email($this->_headers['From']));
922 $this->_set_header('X-Mailer', $this->useragent);
923 $this->_set_header('X-Priority', $this->_priorities[$this->priority - 1]);
924 $this->_set_header('Message-ID', $this->_get_message_id());
925 $this->_set_header('Mime-Version', '1.0');
928 // --------------------------------------------------------------------
931 * Write Headers as a string
936 function _write_headers()
938 if ($this->protocol == 'mail')
940 $this->_subject = $this->_headers['Subject'];
941 unset($this->_headers['Subject']);
944 reset($this->_headers);
945 $this->_header_str = "";
947 foreach($this->_headers as $key => $val)
953 $this->_header_str .= $key.": ".$val.$this->newline;
957 if ($this->_get_protocol() == 'mail')
959 $this->_header_str = rtrim($this->_header_str);
963 // --------------------------------------------------------------------
966 * Build Final Body and attachments
971 function _build_message()
973 if ($this->wordwrap === TRUE AND $this->mailtype != 'html')
975 $this->_body = $this->word_wrap($this->_body);
978 $this->_set_boundaries();
979 $this->_write_headers();
981 $hdr = ($this->_get_protocol() == 'mail') ? $this->newline : '';
983 switch ($this->_get_content_type())
987 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
988 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();
990 if ($this->_get_protocol() == 'mail')
992 $this->_header_str .= $hdr;
993 $this->_finalbody = $this->_body;
998 $hdr .= $this->newline . $this->newline . $this->_body;
1000 $this->_finalbody = $hdr;
1006 if ($this->send_multipart === FALSE)
1008 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1009 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1013 $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline . $this->newline;
1014 $hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
1015 $hdr .= "--" . $this->_alt_boundary . $this->newline;
1017 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1018 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
1019 $hdr .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
1021 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1022 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1025 $this->_body = $this->_prep_quoted_printable($this->_body);
1027 if ($this->_get_protocol() == 'mail')
1029 $this->_header_str .= $hdr;
1030 $this->_finalbody = $this->_body . $this->newline . $this->newline;
1032 if ($this->send_multipart !== FALSE)
1034 $this->_finalbody .= "--" . $this->_alt_boundary . "--";
1040 $hdr .= $this->newline . $this->newline;
1041 $hdr .= $this->_body . $this->newline . $this->newline;
1043 if ($this->send_multipart !== FALSE)
1045 $hdr .= "--" . $this->_alt_boundary . "--";
1048 $this->_finalbody = $hdr;
1052 case 'plain-attach' :
1054 $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline;
1055 $hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
1056 $hdr .= "--" . $this->_atc_boundary . $this->newline;
1058 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1059 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();
1061 if ($this->_get_protocol() == 'mail')
1063 $this->_header_str .= $hdr;
1065 $body = $this->_body . $this->newline . $this->newline;
1068 $hdr .= $this->newline . $this->newline;
1069 $hdr .= $this->_body . $this->newline . $this->newline;
1072 case 'html-attach' :
1074 $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline;
1075 $hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
1076 $hdr .= "--" . $this->_atc_boundary . $this->newline;
1078 $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline .$this->newline;
1079 $hdr .= "--" . $this->_alt_boundary . $this->newline;
1081 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1082 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
1083 $hdr .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
1085 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1086 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1088 $this->_body = $this->_prep_quoted_printable($this->_body);
1090 if ($this->_get_protocol() == 'mail')
1092 $this->_header_str .= $hdr;
1094 $body = $this->_body . $this->newline . $this->newline;
1095 $body .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;
1098 $hdr .= $this->newline . $this->newline;
1099 $hdr .= $this->_body . $this->newline . $this->newline;
1100 $hdr .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;
1105 $attachment = array();
1109 for ($i=0; $i < count($this->_attach_name); $i++)
1111 $filename = $this->_attach_name[$i];
1112 $basename = basename($filename);
1113 $ctype = $this->_attach_type[$i];
1115 if ( ! file_exists($filename))
1117 $this->_set_error_message('email_attachment_missing', $filename);
1121 $h = "--".$this->_atc_boundary.$this->newline;
1122 $h .= "Content-type: ".$ctype."; ";
1123 $h .= "name=\"".$basename."\"".$this->newline;
1124 $h .= "Content-Disposition: ".$this->_attach_disp[$i].";".$this->newline;
1125 $h .= "Content-Transfer-Encoding: base64".$this->newline;
1127 $attachment[$z++] = $h;
1128 $file = filesize($filename) +1;
1130 if ( ! $fp = fopen($filename, FOPEN_READ))
1132 $this->_set_error_message('email_attachment_unreadable', $filename);
1136 $attachment[$z++] = chunk_split(base64_encode(fread($fp, $file)));
1140 if ($this->_get_protocol() == 'mail')
1142 $this->_finalbody = $body . implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";
1147 $this->_finalbody = $hdr.implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";
1152 // --------------------------------------------------------------------
1155 * Prep Quoted Printable
1157 * Prepares string for Quoted-Printable Content-Transfer-Encoding
1158 * Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt
1165 function _prep_quoted_printable($str, $charlim = '')
1167 // Set the character limit
1168 // Don't allow over 76, as that will make servers and MUAs barf
1169 // all over quoted-printable data
1170 if ($charlim == '' OR $charlim > '76')
1175 // Reduce multiple spaces
1176 $str = preg_replace("| +|", " ", $str);
1179 $str = preg_replace('/\x00+/', '', $str);
1181 // Standardize newlines
1182 if (strpos($str, "\r") !== FALSE)
1184 $str = str_replace(array("\r\n", "\r"), "\n", $str);
1187 // We are intentionally wrapping so mail servers will encode characters
1188 // properly and MUAs will behave, so {unwrap} must go!
1189 $str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str);
1191 // Break into an array of lines
1192 $lines = explode("\n", $str);
1197 foreach ($lines as $line)
1199 $length = strlen($line);
1202 // Loop through each character in the line to add soft-wrap
1203 // characters at the end of a line " =\r\n" and add the newly
1204 // processed line(s) to the output (see comment on $crlf class property)
1205 for ($i = 0; $i < $length; $i++)
1207 // Grab the next character
1208 $char = substr($line, $i, 1);
1209 $ascii = ord($char);
1211 // Convert spaces and tabs but only if it's the end of the line
1212 if ($i == ($length - 1))
1214 $char = ($ascii == '32' OR $ascii == '9') ? $escape.sprintf('%02s', dechex($ascii)) : $char;
1220 $char = $escape.strtoupper(sprintf('%02s', dechex($ascii))); // =3D
1223 // If we're at the character limit, add the line to the output,
1224 // reset our temp variable, and keep on chuggin'
1225 if ((strlen($temp) + strlen($char)) >= $charlim)
1227 $output .= $temp.$escape.$this->crlf;
1231 // Add the character to our temporary line
1235 // Add our completed line to the output
1236 $output .= $temp.$this->crlf;
1239 // get rid of extra CRLF tacked onto the end
1240 $output = substr($output, 0, strlen($this->crlf) * -1);
1245 // --------------------------------------------------------------------
1250 * Performs "Q Encoding" on a string for use in email headers. It's related
1251 * but not identical to quoted-printable, so it has its own method
1255 * @param bool // set to TRUE for processing From: headers
1258 function _prep_q_encoding($str, $from = FALSE)
1260 $str = str_replace(array("\r", "\n"), array('', ''), $str);
1262 // Line length must not exceed 76 characters, so we adjust for
1263 // a space, 7 extra characters =??Q??=, and the charset that we will add to each line
1264 $limit = 75 - 7 - strlen($this->charset);
1266 // these special characters must be converted too
1267 $convert = array('_', '=', '?');
1278 for ($i = 0, $length = strlen($str); $i < $length; $i++)
1280 // Grab the next character
1281 $char = substr($str, $i, 1);
1282 $ascii = ord($char);
1284 // convert ALL non-printable ASCII characters and our specials
1285 if ($ascii < 32 OR $ascii > 126 OR in_array($char, $convert))
1287 $char = '='.dechex($ascii);
1290 // handle regular spaces a bit more compactly than =20
1296 // If we're at the character limit, add the line to the output,
1297 // reset our temp variable, and keep on chuggin'
1298 if ((strlen($temp) + strlen($char)) >= $limit)
1300 $output .= $temp.$this->crlf;
1304 // Add the character to our temporary line
1308 $str = $output.$temp;
1310 // wrap each line with the shebang, charset, and transfer encoding
1311 // the preceding space on successive lines is required for header "folding"
1312 $str = trim(preg_replace('/^(.*)$/m', ' =?'.$this->charset.'?Q?$1?=', $str));
1317 // --------------------------------------------------------------------
1327 if ($this->_replyto_flag == FALSE)
1329 $this->reply_to($this->_headers['From']);
1332 if (( ! isset($this->_recipients) AND ! isset($this->_headers['To'])) AND
1333 ( ! isset($this->_bcc_array) AND ! isset($this->_headers['Bcc'])) AND
1334 ( ! isset($this->_headers['Cc'])))
1336 $this->_set_error_message('email_no_recipients');
1340 $this->_build_headers();
1342 if ($this->bcc_batch_mode AND count($this->_bcc_array) > 0)
1344 if (count($this->_bcc_array) > $this->bcc_batch_size)
1345 return $this->batch_bcc_send();
1348 $this->_build_message();
1350 if ( ! $this->_spool_email())
1360 // --------------------------------------------------------------------
1363 * Batch Bcc Send. Sends groups of BCCs in batches
1368 function batch_bcc_send()
1370 $float = $this->bcc_batch_size -1;
1376 for ($i = 0; $i < count($this->_bcc_array); $i++)
1378 if (isset($this->_bcc_array[$i]))
1380 $set .= ", ".$this->_bcc_array[$i];
1385 $chunk[] = substr($set, 1);
1386 $float = $float + $this->bcc_batch_size;
1390 if ($i == count($this->_bcc_array)-1)
1392 $chunk[] = substr($set, 1);
1396 for ($i = 0; $i < count($chunk); $i++)
1398 unset($this->_headers['Bcc']);
1401 $bcc = $this->_str_to_array($chunk[$i]);
1402 $bcc = $this->clean_email($bcc);
1404 if ($this->protocol != 'smtp')
1406 $this->_set_header('Bcc', implode(", ", $bcc));
1410 $this->_bcc_array = $bcc;
1413 $this->_build_message();
1414 $this->_spool_email();
1418 // --------------------------------------------------------------------
1421 * Unwrap special elements
1426 function _unwrap_specials()
1428 $this->_finalbody = preg_replace_callback("/\{unwrap\}(.*?)\{\/unwrap\}/si", array($this, '_remove_nl_callback'), $this->_finalbody);
1431 // --------------------------------------------------------------------
1434 * Strip line-breaks via callback
1439 function _remove_nl_callback($matches)
1441 if (strpos($matches[1], "\r") !== FALSE OR strpos($matches[1], "\n") !== FALSE)
1443 $matches[1] = str_replace(array("\r\n", "\r", "\n"), '', $matches[1]);
1449 // --------------------------------------------------------------------
1452 * Spool mail to the mail server
1457 function _spool_email()
1459 $this->_unwrap_specials();
1461 switch ($this->_get_protocol())
1465 if ( ! $this->_send_with_mail())
1467 $this->_set_error_message('email_send_failure_phpmail');
1473 if ( ! $this->_send_with_sendmail())
1475 $this->_set_error_message('email_send_failure_sendmail');
1481 if ( ! $this->_send_with_smtp())
1483 $this->_set_error_message('email_send_failure_smtp');
1490 $this->_set_error_message('email_sent', $this->_get_protocol());
1494 // --------------------------------------------------------------------
1502 function _send_with_mail()
1504 if ($this->_safe_mode == TRUE)
1506 if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str))
1517 // most documentation of sendmail using the "-f" flag lacks a space after it, however
1518 // we've encountered servers that seem to require it to be in place.
1519 if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, "-f ".$this->clean_email($this->_headers['From'])))
1530 // --------------------------------------------------------------------
1533 * Send using Sendmail
1538 function _send_with_sendmail()
1540 $fp = @popen($this->mailpath . " -oi -f ".$this->clean_email($this->_headers['From'])." -t", 'w');
1542 if ($fp === FALSE OR $fp === NULL)
1544 // server probably has popen disabled, so nothing we can do to get a verbose error.
1548 fputs($fp, $this->_header_str);
1549 fputs($fp, $this->_finalbody);
1551 $status = pclose($fp);
1553 if (version_compare(PHP_VERSION, '4.2.3') == -1)
1555 $status = $status >> 8 & 0xFF;
1560 $this->_set_error_message('email_exit_status', $status);
1561 $this->_set_error_message('email_no_socket');
1568 // --------------------------------------------------------------------
1576 function _send_with_smtp()
1578 if ($this->smtp_host == '')
1580 $this->_set_error_message('email_no_hostname');
1584 $this->_smtp_connect();
1585 $this->_smtp_authenticate();
1587 $this->_send_command('from', $this->clean_email($this->_headers['From']));
1589 foreach($this->_recipients as $val)
1591 $this->_send_command('to', $val);
1594 if (count($this->_cc_array) > 0)
1596 foreach($this->_cc_array as $val)
1600 $this->_send_command('to', $val);
1605 if (count($this->_bcc_array) > 0)
1607 foreach($this->_bcc_array as $val)
1611 $this->_send_command('to', $val);
1616 $this->_send_command('data');
1618 // perform dot transformation on any lines that begin with a dot
1619 $this->_send_data($this->_header_str . preg_replace('/^\./m', '..$1', $this->_finalbody));
1621 $this->_send_data('.');
1623 $reply = $this->_get_smtp_data();
1625 $this->_set_error_message($reply);
1627 if (strncmp($reply, '250', 3) != 0)
1629 $this->_set_error_message('email_smtp_error', $reply);
1633 $this->_send_command('quit');
1637 // --------------------------------------------------------------------
1646 function _smtp_connect()
1648 $this->_smtp_connect = fsockopen($this->smtp_host,
1652 $this->smtp_timeout);
1654 if( ! is_resource($this->_smtp_connect))
1656 $this->_set_error_message('email_smtp_error', $errno." ".$errstr);
1660 $this->_set_error_message($this->_get_smtp_data());
1661 return $this->_send_command('hello');
1664 // --------------------------------------------------------------------
1674 function _send_command($cmd, $data = '')
1680 if ($this->_smtp_auth OR $this->_get_encoding() == '8bit')
1681 $this->_send_data('EHLO '.$this->_get_hostname());
1683 $this->_send_data('HELO '.$this->_get_hostname());
1689 $this->_send_data('MAIL FROM:<'.$data.'>');
1695 $this->_send_data('RCPT TO:<'.$data.'>');
1701 $this->_send_data('DATA');
1707 $this->_send_data('QUIT');
1713 $reply = $this->_get_smtp_data();
1715 $this->_debug_msg[] = "<pre>".$cmd.": ".$reply."</pre>";
1717 if (substr($reply, 0, 3) != $resp)
1719 $this->_set_error_message('email_smtp_error', $reply);
1725 fclose($this->_smtp_connect);
1731 // --------------------------------------------------------------------
1739 function _smtp_authenticate()
1741 if ( ! $this->_smtp_auth)
1746 if ($this->smtp_user == "" AND $this->smtp_pass == "")
1748 $this->_set_error_message('email_no_smtp_unpw');
1752 $this->_send_data('AUTH LOGIN');
1754 $reply = $this->_get_smtp_data();
1756 if (strncmp($reply, '334', 3) != 0)
1758 $this->_set_error_message('email_failed_smtp_login', $reply);
1762 $this->_send_data(base64_encode($this->smtp_user));
1764 $reply = $this->_get_smtp_data();
1766 if (strncmp($reply, '334', 3) != 0)
1768 $this->_set_error_message('email_smtp_auth_un', $reply);
1772 $this->_send_data(base64_encode($this->smtp_pass));
1774 $reply = $this->_get_smtp_data();
1776 if (strncmp($reply, '235', 3) != 0)
1778 $this->_set_error_message('email_smtp_auth_pw', $reply);
1785 // --------------------------------------------------------------------
1793 function _send_data($data)
1795 if ( ! fwrite($this->_smtp_connect, $data . $this->newline))
1797 $this->_set_error_message('email_smtp_data_failure', $data);
1806 // --------------------------------------------------------------------
1814 function _get_smtp_data()
1818 while ($str = fgets($this->_smtp_connect, 512))
1822 if (substr($str, 3, 1) == " ")
1831 // --------------------------------------------------------------------
1839 function _get_hostname()
1841 return (isset($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain';
1844 // --------------------------------------------------------------------
1854 if ($this->_IP !== FALSE)
1859 $cip = (isset($_SERVER['HTTP_CLIENT_IP']) AND $_SERVER['HTTP_CLIENT_IP'] != "") ? $_SERVER['HTTP_CLIENT_IP'] : FALSE;
1860 $rip = (isset($_SERVER['REMOTE_ADDR']) AND $_SERVER['REMOTE_ADDR'] != "") ? $_SERVER['REMOTE_ADDR'] : FALSE;
1861 $fip = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND $_SERVER['HTTP_X_FORWARDED_FOR'] != "") ? $_SERVER['HTTP_X_FORWARDED_FOR'] : FALSE;
1863 if ($cip && $rip) $this->_IP = $cip;
1864 elseif ($rip) $this->_IP = $rip;
1865 elseif ($cip) $this->_IP = $cip;
1866 elseif ($fip) $this->_IP = $fip;
1868 if (strstr($this->_IP, ','))
1870 $x = explode(',', $this->_IP);
1871 $this->_IP = end($x);
1874 if ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $this->_IP))
1876 $this->_IP = '0.0.0.0';
1886 // --------------------------------------------------------------------
1894 function print_debugger()
1898 if (count($this->_debug_msg) > 0)
1900 foreach ($this->_debug_msg as $val)
1906 $msg .= "<pre>".$this->_header_str."\n".htmlspecialchars($this->_subject)."\n".htmlspecialchars($this->_finalbody).'</pre>';
1910 // --------------------------------------------------------------------
1919 function _set_error_message($msg, $val = '')
1921 $CI =& get_instance();
1922 $CI->lang->load('email');
1924 if (FALSE === ($line = $CI->lang->line($msg)))
1926 $this->_debug_msg[] = str_replace('%s', $val, $msg)."<br />";
1930 $this->_debug_msg[] = str_replace('%s', $val, $line)."<br />";
1934 // --------------------------------------------------------------------
1943 function _mime_types($ext = "")
1945 $mimes = array( 'hqx' => 'application/mac-binhex40',
1946 'cpt' => 'application/mac-compactpro',
1947 'doc' => 'application/msword',
1948 'bin' => 'application/macbinary',
1949 'dms' => 'application/octet-stream',
1950 'lha' => 'application/octet-stream',
1951 'lzh' => 'application/octet-stream',
1952 'exe' => 'application/octet-stream',
1953 'class' => 'application/octet-stream',
1954 'psd' => 'application/octet-stream',
1955 'so' => 'application/octet-stream',
1956 'sea' => 'application/octet-stream',
1957 'dll' => 'application/octet-stream',
1958 'oda' => 'application/oda',
1959 'pdf' => 'application/pdf',
1960 'ai' => 'application/postscript',
1961 'eps' => 'application/postscript',
1962 'ps' => 'application/postscript',
1963 'smi' => 'application/smil',
1964 'smil' => 'application/smil',
1965 'mif' => 'application/vnd.mif',
1966 'xls' => 'application/vnd.ms-excel',
1967 'ppt' => 'application/vnd.ms-powerpoint',
1968 'wbxml' => 'application/vnd.wap.wbxml',
1969 'wmlc' => 'application/vnd.wap.wmlc',
1970 'dcr' => 'application/x-director',
1971 'dir' => 'application/x-director',
1972 'dxr' => 'application/x-director',
1973 'dvi' => 'application/x-dvi',
1974 'gtar' => 'application/x-gtar',
1975 'php' => 'application/x-httpd-php',
1976 'php4' => 'application/x-httpd-php',
1977 'php3' => 'application/x-httpd-php',
1978 'phtml' => 'application/x-httpd-php',
1979 'phps' => 'application/x-httpd-php-source',
1980 'js' => 'application/x-javascript',
1981 'swf' => 'application/x-shockwave-flash',
1982 'sit' => 'application/x-stuffit',
1983 'tar' => 'application/x-tar',
1984 'tgz' => 'application/x-tar',
1985 'xhtml' => 'application/xhtml+xml',
1986 'xht' => 'application/xhtml+xml',
1987 'zip' => 'application/zip',
1988 'mid' => 'audio/midi',
1989 'midi' => 'audio/midi',
1990 'mpga' => 'audio/mpeg',
1991 'mp2' => 'audio/mpeg',
1992 'mp3' => 'audio/mpeg',
1993 'aif' => 'audio/x-aiff',
1994 'aiff' => 'audio/x-aiff',
1995 'aifc' => 'audio/x-aiff',
1996 'ram' => 'audio/x-pn-realaudio',
1997 'rm' => 'audio/x-pn-realaudio',
1998 'rpm' => 'audio/x-pn-realaudio-plugin',
1999 'ra' => 'audio/x-realaudio',
2000 'rv' => 'video/vnd.rn-realvideo',
2001 'wav' => 'audio/x-wav',
2002 'bmp' => 'image/bmp',
2003 'gif' => 'image/gif',
2004 'jpeg' => 'image/jpeg',
2005 'jpg' => 'image/jpeg',
2006 'jpe' => 'image/jpeg',
2007 'png' => 'image/png',
2008 'tiff' => 'image/tiff',
2009 'tif' => 'image/tiff',
2010 'css' => 'text/css',
2011 'html' => 'text/html',
2012 'htm' => 'text/html',
2013 'shtml' => 'text/html',
2014 'txt' => 'text/plain',
2015 'text' => 'text/plain',
2016 'log' => 'text/plain',
2017 'rtx' => 'text/richtext',
2018 'rtf' => 'text/rtf',
2019 'xml' => 'text/xml',
2020 'xsl' => 'text/xml',
2021 'mpeg' => 'video/mpeg',
2022 'mpg' => 'video/mpeg',
2023 'mpe' => 'video/mpeg',
2024 'qt' => 'video/quicktime',
2025 'mov' => 'video/quicktime',
2026 'avi' => 'video/x-msvideo',
2027 'movie' => 'video/x-sgi-movie',
2028 'doc' => 'application/msword',
2029 'word' => 'application/msword',
2030 'xl' => 'application/excel',
2031 'eml' => 'message/rfc822'
2034 return ( ! isset($mimes[strtolower($ext)])) ? "application/x-unknown-content-type" : $mimes[strtolower($ext)];
2038 // END CI_Email class
2040 /* End of file Email.php */
2041 /* Location: ./system/libraries/Email.php */