1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, 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 public function __construct($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 public function initialize($config = array())
111 foreach ($config as $key => $val)
113 if (isset($this->$key))
115 $method = 'set_'.$key;
117 if (method_exists($this, $method))
119 $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;
135 // --------------------------------------------------------------------
138 * Initialize the Email Data
143 public function clear($clear_attachments = FALSE)
145 $this->_subject = "";
147 $this->_finalbody = "";
148 $this->_header_str = "";
149 $this->_replyto_flag = FALSE;
150 $this->_recipients = array();
151 $this->_cc_array = array();
152 $this->_bcc_array = array();
153 $this->_headers = array();
154 $this->_debug_msg = array();
156 $this->_set_header('User-Agent', $this->useragent);
157 $this->_set_header('Date', $this->_set_date());
159 if ($clear_attachments !== FALSE)
161 $this->_attach_name = array();
162 $this->_attach_type = array();
163 $this->_attach_disp = array();
169 // --------------------------------------------------------------------
179 public function from($from, $name = '')
181 if (preg_match( '/\<(.*)\>/', $from, $match))
188 $this->validate_email($this->_str_to_array($from));
191 // prepare the display name
194 // only use Q encoding if there are characters that would require it
195 if ( ! preg_match('/[\200-\377]/', $name))
197 // add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
198 $name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
202 $name = $this->_prep_q_encoding($name, TRUE);
206 $this->_set_header('From', $name.' <'.$from.'>');
207 $this->_set_header('Return-Path', '<'.$from.'>');
212 // --------------------------------------------------------------------
222 public function reply_to($replyto, $name = '')
224 if (preg_match( '/\<(.*)\>/', $replyto, $match))
226 $replyto = $match['1'];
231 $this->validate_email($this->_str_to_array($replyto));
239 if (strncmp($name, '"', 1) != 0)
241 $name = '"'.$name.'"';
244 $this->_set_header('Reply-To', $name.' <'.$replyto.'>');
245 $this->_replyto_flag = TRUE;
250 // --------------------------------------------------------------------
259 public function to($to)
261 $to = $this->_str_to_array($to);
262 $to = $this->clean_email($to);
266 $this->validate_email($to);
269 if ($this->_get_protocol() != 'mail')
271 $this->_set_header('To', implode(", ", $to));
274 switch ($this->_get_protocol())
277 $this->_recipients = $to;
281 $this->_recipients = implode(", ", $to);
288 // --------------------------------------------------------------------
297 public function cc($cc)
299 $cc = $this->_str_to_array($cc);
300 $cc = $this->clean_email($cc);
304 $this->validate_email($cc);
307 $this->_set_header('Cc', implode(", ", $cc));
309 if ($this->_get_protocol() == "smtp")
311 $this->_cc_array = $cc;
317 // --------------------------------------------------------------------
327 public function bcc($bcc, $limit = '')
329 if ($limit != '' && is_numeric($limit))
331 $this->bcc_batch_mode = TRUE;
332 $this->bcc_batch_size = $limit;
335 $bcc = $this->_str_to_array($bcc);
336 $bcc = $this->clean_email($bcc);
340 $this->validate_email($bcc);
343 if (($this->_get_protocol() == "smtp") OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
345 $this->_bcc_array = $bcc;
349 $this->_set_header('Bcc', implode(", ", $bcc));
355 // --------------------------------------------------------------------
364 public function subject($subject)
366 $subject = $this->_prep_q_encoding($subject);
367 $this->_set_header('Subject', $subject);
371 // --------------------------------------------------------------------
380 public function message($body)
382 $this->_body = stripslashes(rtrim(str_replace("\r", "", $body)));
386 // --------------------------------------------------------------------
389 * Assign file attachments
395 public function attach($filename, $disposition = 'attachment')
397 $this->_attach_name[] = $filename;
398 $this->_attach_type[] = $this->_mime_types(next(explode('.', basename($filename))));
399 $this->_attach_disp[] = $disposition; // Can also be 'inline' Not sure if it matters
403 // --------------------------------------------------------------------
413 private function _set_header($header, $value)
415 $this->_headers[$header] = $value;
418 // --------------------------------------------------------------------
421 * Convert a String to an Array
427 private function _str_to_array($email)
429 if ( ! is_array($email))
431 if (strpos($email, ',') !== FALSE)
433 $email = preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY);
437 $email = trim($email);
438 settype($email, "array");
444 // --------------------------------------------------------------------
447 * Set Multipart Value
453 public function set_alt_message($str = '')
455 $this->alt_message = ($str == '') ? '' : $str;
459 // --------------------------------------------------------------------
468 public function set_mailtype($type = 'text')
470 $this->mailtype = ($type == 'html') ? 'html' : 'text';
474 // --------------------------------------------------------------------
483 public function set_wordwrap($wordwrap = TRUE)
485 $this->wordwrap = ($wordwrap === FALSE) ? FALSE : TRUE;
489 // --------------------------------------------------------------------
498 public function set_protocol($protocol = 'mail')
500 $this->protocol = ( ! in_array($protocol, $this->_protocols, TRUE)) ? 'mail' : strtolower($protocol);
504 // --------------------------------------------------------------------
513 public function set_priority($n = 3)
515 if ( ! is_numeric($n))
521 if ($n < 1 OR $n > 5)
527 $this->priority = $n;
531 // --------------------------------------------------------------------
534 * Set Newline Character
540 public function set_newline($newline = "\n")
542 if ($newline != "\n" AND $newline != "\r\n" AND $newline != "\r")
544 $this->newline = "\n";
548 $this->newline = $newline;
553 // --------------------------------------------------------------------
562 public function set_crlf($crlf = "\n")
564 if ($crlf != "\n" AND $crlf != "\r\n" AND $crlf != "\r")
575 // --------------------------------------------------------------------
578 * Set Message Boundary
583 private function _set_boundaries()
585 $this->_alt_boundary = "B_ALT_".uniqid(''); // multipart/alternative
586 $this->_atc_boundary = "B_ATC_".uniqid(''); // attachment boundary
589 // --------------------------------------------------------------------
597 private function _get_message_id()
599 $from = $this->_headers['Return-Path'];
600 $from = str_replace(">", "", $from);
601 $from = str_replace("<", "", $from);
603 return "<".uniqid('').strstr($from, '@').">";
606 // --------------------------------------------------------------------
615 private function _get_protocol($return = TRUE)
617 $this->protocol = strtolower($this->protocol);
618 $this->protocol = ( ! in_array($this->protocol, $this->_protocols, TRUE)) ? 'mail' : $this->protocol;
622 return $this->protocol;
626 // --------------------------------------------------------------------
635 private function _get_encoding($return = TRUE)
637 $this->_encoding = ( ! in_array($this->_encoding, $this->_bit_depths)) ? '8bit' : $this->_encoding;
639 foreach ($this->_base_charsets as $charset)
641 if (strncmp($charset, $this->charset, strlen($charset)) == 0)
643 $this->_encoding = '7bit';
649 return $this->_encoding;
653 // --------------------------------------------------------------------
656 * Get content type (text/html/attachment)
661 private function _get_content_type()
663 if ($this->mailtype == 'html' && count($this->_attach_name) == 0)
667 elseif ($this->mailtype == 'html' && count($this->_attach_name) > 0)
669 return 'html-attach';
671 elseif ($this->mailtype == 'text' && count($this->_attach_name) > 0)
673 return 'plain-attach';
681 // --------------------------------------------------------------------
689 private function _set_date()
691 $timezone = date("Z");
692 $operator = (strncmp($timezone, '-', 1) == 0) ? '-' : '+';
693 $timezone = abs($timezone);
694 $timezone = floor($timezone/3600) * 100 + ($timezone % 3600 ) / 60;
696 return sprintf("%s %s%04d", date("D, j M Y H:i:s"), $operator, $timezone);
699 // --------------------------------------------------------------------
707 private function _get_mime_message()
709 return "This is a multi-part message in MIME format.".$this->newline."Your email application may not support this format.";
712 // --------------------------------------------------------------------
715 * Validate Email Address
721 public function validate_email($email)
723 if ( ! is_array($email))
725 $this->_set_error_message('email_must_be_array');
729 foreach ($email as $val)
731 if ( ! $this->valid_email($val))
733 $this->_set_error_message('email_invalid_address', $val);
741 // --------------------------------------------------------------------
750 public function valid_email($address)
752 return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
755 // --------------------------------------------------------------------
758 * Clean Extended Email Address: Joe Smith <joe@smith.com>
764 public function clean_email($email)
766 if ( ! is_array($email))
768 if (preg_match('/\<(.*)\>/', $email, $match))
778 $clean_email = array();
780 foreach ($email as $addy)
782 if (preg_match( '/\<(.*)\>/', $addy, $match))
784 $clean_email[] = $match['1'];
788 $clean_email[] = $addy;
795 // --------------------------------------------------------------------
798 * Build alternative plain text message
800 * This public function provides the raw message for use
801 * in plain-text headers of HTML-formatted emails.
802 * If the user hasn't specified his own alternative message
803 * it creates one by stripping the HTML
808 private function _get_alt_message()
810 if ($this->alt_message != "")
812 return $this->word_wrap($this->alt_message, '76');
815 if (preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match))
821 $body = $this->_body;
824 $body = trim(strip_tags($body));
825 $body = preg_replace( '#<!--(.*)--\>#', "", $body);
826 $body = str_replace("\t", "", $body);
828 for ($i = 20; $i >= 3; $i--)
832 for ($x = 1; $x <= $i; $x ++)
837 $body = str_replace($n, "\n\n", $body);
840 return $this->word_wrap($body, '76');
843 // --------------------------------------------------------------------
853 public function word_wrap($str, $charlim = '')
855 // Se the character limit
858 $charlim = ($this->wrapchars == "") ? "76" : $this->wrapchars;
861 // Reduce multiple spaces
862 $str = preg_replace("| +|", " ", $str);
864 // Standardize newlines
865 if (strpos($str, "\r") !== FALSE)
867 $str = str_replace(array("\r\n", "\r"), "\n", $str);
870 // If the current word is surrounded by {unwrap} tags we'll
871 // strip the entire chunk and replace it with a marker.
873 if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches))
875 for ($i = 0; $i < count($matches['0']); $i++)
877 $unwrap[] = $matches['1'][$i];
878 $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str);
882 // Use PHP's native public function to do the initial wordwrap.
883 // We set the cut flag to FALSE so that any individual words that are
884 // too long get left alone. In the next step we'll deal with them.
885 $str = wordwrap($str, $charlim, "\n", FALSE);
887 // Split the string into individual lines of text and cycle through them
889 foreach (explode("\n", $str) as $line)
891 // Is the line within the allowed character count?
892 // If so we'll join it to the output and continue
893 if (strlen($line) <= $charlim)
895 $output .= $line.$this->newline;
900 while ((strlen($line)) > $charlim)
902 // If the over-length word is a URL we won't wrap it
903 if (preg_match("!\[url.+\]|://|wwww.!", $line))
908 // Trim the word down
909 $temp .= substr($line, 0, $charlim-1);
910 $line = substr($line, $charlim-1);
913 // If $temp contains data it means we had to split up an over-length
914 // word into smaller chunks so we'll add it back to our current line
917 $output .= $temp.$this->newline.$line;
924 $output .= $this->newline;
927 // Put our markers back
928 if (count($unwrap) > 0)
930 foreach ($unwrap as $key => $val)
932 $output = str_replace("{{unwrapped".$key."}}", $val, $output);
939 // --------------------------------------------------------------------
942 * Build final headers
948 private function _build_headers()
950 $this->_set_header('X-Sender', $this->clean_email($this->_headers['From']));
951 $this->_set_header('X-Mailer', $this->useragent);
952 $this->_set_header('X-Priority', $this->_priorities[$this->priority - 1]);
953 $this->_set_header('Message-ID', $this->_get_message_id());
954 $this->_set_header('Mime-Version', '1.0');
957 // --------------------------------------------------------------------
960 * Write Headers as a string
965 private function _write_headers()
967 if ($this->protocol == 'mail')
969 $this->_subject = $this->_headers['Subject'];
970 unset($this->_headers['Subject']);
973 reset($this->_headers);
974 $this->_header_str = "";
976 foreach ($this->_headers as $key => $val)
982 $this->_header_str .= $key.": ".$val.$this->newline;
986 if ($this->_get_protocol() == 'mail')
988 $this->_header_str = rtrim($this->_header_str);
992 // --------------------------------------------------------------------
995 * Build Final Body and attachments
1000 private function _build_message()
1002 if ($this->wordwrap === TRUE AND $this->mailtype != 'html')
1004 $this->_body = $this->word_wrap($this->_body);
1007 $this->_set_boundaries();
1008 $this->_write_headers();
1010 $hdr = ($this->_get_protocol() == 'mail') ? $this->newline : '';
1013 switch ($this->_get_content_type())
1017 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1018 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();
1020 if ($this->_get_protocol() == 'mail')
1022 $this->_header_str .= $hdr;
1023 $this->_finalbody = $this->_body;
1027 $this->_finalbody = $hdr . $this->newline . $this->newline . $this->_body;
1035 if ($this->send_multipart === FALSE)
1037 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1038 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1042 $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline . $this->newline;
1044 $body .= $this->_get_mime_message() . $this->newline . $this->newline;
1045 $body .= "--" . $this->_alt_boundary . $this->newline;
1047 $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1048 $body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
1049 $body .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
1051 $body .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1052 $body .= "Content-Transfer-Encoding: quoted-printable" . $this->newline . $this->newline;
1055 $this->_finalbody = $body . $this->_prep_quoted_printable($this->_body) . $this->newline . $this->newline;
1058 if ($this->_get_protocol() == 'mail')
1060 $this->_header_str .= $hdr;
1064 $this->_finalbody = $hdr . $this->_finalbody;
1068 if ($this->send_multipart !== FALSE)
1070 $this->_finalbody .= "--" . $this->_alt_boundary . "--";
1076 case 'plain-attach' :
1078 $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline;
1080 if ($this->_get_protocol() == 'mail')
1082 $this->_header_str .= $hdr;
1085 $body .= $this->_get_mime_message() . $this->newline . $this->newline;
1086 $body .= "--" . $this->_atc_boundary . $this->newline;
1088 $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1089 $body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
1091 $body .= $this->_body . $this->newline . $this->newline;
1094 case 'html-attach' :
1096 $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline;
1098 if ($this->_get_protocol() == 'mail')
1100 $this->_header_str .= $hdr;
1103 $body .= $this->_get_mime_message() . $this->newline . $this->newline;
1104 $body .= "--" . $this->_atc_boundary . $this->newline;
1106 $body .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline .$this->newline;
1107 $body .= "--" . $this->_alt_boundary . $this->newline;
1109 $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1110 $body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
1111 $body .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
1113 $body .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1114 $body .= "Content-Transfer-Encoding: quoted-printable" . $this->newline . $this->newline;
1116 $body .= $this->_prep_quoted_printable($this->_body) . $this->newline . $this->newline;
1117 $body .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;
1122 $attachment = array();
1126 for ($i=0; $i < count($this->_attach_name); $i++)
1128 $filename = $this->_attach_name[$i];
1129 $basename = basename($filename);
1130 $ctype = $this->_attach_type[$i];
1132 if ( ! file_exists($filename))
1134 $this->_set_error_message('email_attachment_missing', $filename);
1138 $h = "--".$this->_atc_boundary.$this->newline;
1139 $h .= "Content-type: ".$ctype."; ";
1140 $h .= "name=\"".$basename."\"".$this->newline;
1141 $h .= "Content-Disposition: ".$this->_attach_disp[$i].";".$this->newline;
1142 $h .= "Content-Transfer-Encoding: base64".$this->newline;
1144 $attachment[$z++] = $h;
1145 $file = filesize($filename) +1;
1147 if ( ! $fp = fopen($filename, FOPEN_READ))
1149 $this->_set_error_message('email_attachment_unreadable', $filename);
1153 $attachment[$z++] = chunk_split(base64_encode(fread($fp, $file)));
1157 $body .= implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";
1160 if ($this->_get_protocol() == 'mail')
1162 $this->_finalbody = $body;
1166 $this->_finalbody = $hdr . $body;
1172 // --------------------------------------------------------------------
1175 * Prep Quoted Printable
1177 * Prepares string for Quoted-Printable Content-Transfer-Encoding
1178 * Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt
1185 private function _prep_quoted_printable($str, $charlim = '')
1187 // Set the character limit
1188 // Don't allow over 76, as that will make servers and MUAs barf
1189 // all over quoted-printable data
1190 if ($charlim == '' OR $charlim > '76')
1195 // Reduce multiple spaces
1196 $str = preg_replace("| +|", " ", $str);
1199 $str = preg_replace('/\x00+/', '', $str);
1201 // Standardize newlines
1202 if (strpos($str, "\r") !== FALSE)
1204 $str = str_replace(array("\r\n", "\r"), "\n", $str);
1207 // We are intentionally wrapping so mail servers will encode characters
1208 // properly and MUAs will behave, so {unwrap} must go!
1209 $str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str);
1211 // Break into an array of lines
1212 $lines = explode("\n", $str);
1217 foreach ($lines as $line)
1219 $length = strlen($line);
1222 // Loop through each character in the line to add soft-wrap
1223 // characters at the end of a line " =\r\n" and add the newly
1224 // processed line(s) to the output (see comment on $crlf class property)
1225 for ($i = 0; $i < $length; $i++)
1227 // Grab the next character
1228 $char = substr($line, $i, 1);
1229 $ascii = ord($char);
1231 // Convert spaces and tabs but only if it's the end of the line
1232 if ($i == ($length - 1))
1234 $char = ($ascii == '32' OR $ascii == '9') ? $escape.sprintf('%02s', dechex($ascii)) : $char;
1240 $char = $escape.strtoupper(sprintf('%02s', dechex($ascii))); // =3D
1243 // If we're at the character limit, add the line to the output,
1244 // reset our temp variable, and keep on chuggin'
1245 if ((strlen($temp) + strlen($char)) >= $charlim)
1247 $output .= $temp.$escape.$this->crlf;
1251 // Add the character to our temporary line
1255 // Add our completed line to the output
1256 $output .= $temp.$this->crlf;
1259 // get rid of extra CRLF tacked onto the end
1260 $output = substr($output, 0, strlen($this->crlf) * -1);
1265 // --------------------------------------------------------------------
1270 * Performs "Q Encoding" on a string for use in email headers. It's related
1271 * but not identical to quoted-printable, so it has its own method
1275 * @param bool // set to TRUE for processing From: headers
1278 private function _prep_q_encoding($str, $from = FALSE)
1280 $str = str_replace(array("\r", "\n"), array('', ''), $str);
1282 // Line length must not exceed 76 characters, so we adjust for
1283 // a space, 7 extra characters =??Q??=, and the charset that we will add to each line
1284 $limit = 75 - 7 - strlen($this->charset);
1286 // these special characters must be converted too
1287 $convert = array('_', '=', '?');
1298 for ($i = 0, $length = strlen($str); $i < $length; $i++)
1300 // Grab the next character
1301 $char = substr($str, $i, 1);
1302 $ascii = ord($char);
1304 // convert ALL non-printable ASCII characters and our specials
1305 if ($ascii < 32 OR $ascii > 126 OR in_array($char, $convert))
1307 $char = '='.dechex($ascii);
1310 // handle regular spaces a bit more compactly than =20
1316 // If we're at the character limit, add the line to the output,
1317 // reset our temp variable, and keep on chuggin'
1318 if ((strlen($temp) + strlen($char)) >= $limit)
1320 $output .= $temp.$this->crlf;
1324 // Add the character to our temporary line
1328 $str = $output.$temp;
1330 // wrap each line with the shebang, charset, and transfer encoding
1331 // the preceding space on successive lines is required for header "folding"
1332 $str = trim(preg_replace('/^(.*)$/m', ' =?'.$this->charset.'?Q?$1?=', $str));
1337 // --------------------------------------------------------------------
1345 public function send()
1347 if ($this->_replyto_flag == FALSE)
1349 $this->reply_to($this->_headers['From']);
1352 if (( ! isset($this->_recipients) AND ! isset($this->_headers['To'])) AND
1353 ( ! isset($this->_bcc_array) AND ! isset($this->_headers['Bcc'])) AND
1354 ( ! isset($this->_headers['Cc'])))
1356 $this->_set_error_message('email_no_recipients');
1360 $this->_build_headers();
1362 if ($this->bcc_batch_mode AND count($this->_bcc_array) > 0)
1364 if (count($this->_bcc_array) > $this->bcc_batch_size)
1365 return $this->batch_bcc_send();
1368 $this->_build_message();
1370 if ( ! $this->_spool_email())
1380 // --------------------------------------------------------------------
1383 * Batch Bcc Send. Sends groups of BCCs in batches
1388 public function batch_bcc_send()
1390 $float = $this->bcc_batch_size -1;
1396 for ($i = 0; $i < count($this->_bcc_array); $i++)
1398 if (isset($this->_bcc_array[$i]))
1400 $set .= ", ".$this->_bcc_array[$i];
1405 $chunk[] = substr($set, 1);
1406 $float = $float + $this->bcc_batch_size;
1410 if ($i == count($this->_bcc_array)-1)
1412 $chunk[] = substr($set, 1);
1416 for ($i = 0; $i < count($chunk); $i++)
1418 unset($this->_headers['Bcc']);
1421 $bcc = $this->_str_to_array($chunk[$i]);
1422 $bcc = $this->clean_email($bcc);
1424 if ($this->protocol != 'smtp')
1426 $this->_set_header('Bcc', implode(", ", $bcc));
1430 $this->_bcc_array = $bcc;
1433 $this->_build_message();
1434 $this->_spool_email();
1438 // --------------------------------------------------------------------
1441 * Unwrap special elements
1446 private function _unwrap_specials()
1448 $this->_finalbody = preg_replace_callback("/\{unwrap\}(.*?)\{\/unwrap\}/si", array($this, '_remove_nl_callback'), $this->_finalbody);
1451 // --------------------------------------------------------------------
1454 * Strip line-breaks via callback
1459 private function _remove_nl_callback($matches)
1461 if (strpos($matches[1], "\r") !== FALSE OR strpos($matches[1], "\n") !== FALSE)
1463 $matches[1] = str_replace(array("\r\n", "\r", "\n"), '', $matches[1]);
1469 // --------------------------------------------------------------------
1472 * Spool mail to the mail server
1477 private function _spool_email()
1479 $this->_unwrap_specials();
1481 switch ($this->_get_protocol())
1485 if ( ! $this->_send_with_mail())
1487 $this->_set_error_message('email_send_failure_phpmail');
1493 if ( ! $this->_send_with_sendmail())
1495 $this->_set_error_message('email_send_failure_sendmail');
1501 if ( ! $this->_send_with_smtp())
1503 $this->_set_error_message('email_send_failure_smtp');
1510 $this->_set_error_message('email_sent', $this->_get_protocol());
1514 // --------------------------------------------------------------------
1522 private function _send_with_mail()
1524 if ($this->_safe_mode == TRUE)
1526 if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str))
1537 // most documentation of sendmail using the "-f" flag lacks a space after it, however
1538 // we've encountered servers that seem to require it to be in place.
1540 if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, "-f ".$this->clean_email($this->_headers['From'])))
1551 // --------------------------------------------------------------------
1554 * Send using Sendmail
1559 private function _send_with_sendmail()
1561 $fp = @popen($this->mailpath . " -oi -f ".$this->clean_email($this->_headers['From'])." -t", 'w');
1563 if ($fp === FALSE OR $fp === NULL)
1565 // server probably has popen disabled, so nothing we can do to get a verbose error.
1569 fputs($fp, $this->_header_str);
1570 fputs($fp, $this->_finalbody);
1572 $status = pclose($fp);
1574 if (version_compare(PHP_VERSION, '4.2.3') == -1)
1576 $status = $status >> 8 & 0xFF;
1581 $this->_set_error_message('email_exit_status', $status);
1582 $this->_set_error_message('email_no_socket');
1589 // --------------------------------------------------------------------
1597 private function _send_with_smtp()
1599 if ($this->smtp_host == '')
1601 $this->_set_error_message('email_no_hostname');
1605 $this->_smtp_connect();
1606 $this->_smtp_authenticate();
1608 $this->_send_command('from', $this->clean_email($this->_headers['From']));
1610 foreach ($this->_recipients as $val)
1612 $this->_send_command('to', $val);
1615 if (count($this->_cc_array) > 0)
1617 foreach ($this->_cc_array as $val)
1621 $this->_send_command('to', $val);
1626 if (count($this->_bcc_array) > 0)
1628 foreach ($this->_bcc_array as $val)
1632 $this->_send_command('to', $val);
1637 $this->_send_command('data');
1639 // perform dot transformation on any lines that begin with a dot
1640 $this->_send_data($this->_header_str . preg_replace('/^\./m', '..$1', $this->_finalbody));
1642 $this->_send_data('.');
1644 $reply = $this->_get_smtp_data();
1646 $this->_set_error_message($reply);
1648 if (strncmp($reply, '250', 3) != 0)
1650 $this->_set_error_message('email_smtp_error', $reply);
1654 $this->_send_command('quit');
1658 // --------------------------------------------------------------------
1667 private function _smtp_connect()
1669 $this->_smtp_connect = fsockopen($this->smtp_host,
1673 $this->smtp_timeout);
1675 if ( ! is_resource($this->_smtp_connect))
1677 $this->_set_error_message('email_smtp_error', $errno." ".$errstr);
1681 $this->_set_error_message($this->_get_smtp_data());
1682 return $this->_send_command('hello');
1685 // --------------------------------------------------------------------
1695 private function _send_command($cmd, $data = '')
1701 if ($this->_smtp_auth OR $this->_get_encoding() == '8bit')
1702 $this->_send_data('EHLO '.$this->_get_hostname());
1704 $this->_send_data('HELO '.$this->_get_hostname());
1710 $this->_send_data('MAIL FROM:<'.$data.'>');
1716 $this->_send_data('RCPT TO:<'.$data.'>');
1722 $this->_send_data('DATA');
1728 $this->_send_data('QUIT');
1734 $reply = $this->_get_smtp_data();
1736 $this->_debug_msg[] = "<pre>".$cmd.": ".$reply."</pre>";
1738 if (substr($reply, 0, 3) != $resp)
1740 $this->_set_error_message('email_smtp_error', $reply);
1746 fclose($this->_smtp_connect);
1752 // --------------------------------------------------------------------
1760 private function _smtp_authenticate()
1762 if ( ! $this->_smtp_auth)
1767 if ($this->smtp_user == "" AND $this->smtp_pass == "")
1769 $this->_set_error_message('email_no_smtp_unpw');
1773 $this->_send_data('AUTH LOGIN');
1775 $reply = $this->_get_smtp_data();
1777 if (strncmp($reply, '334', 3) != 0)
1779 $this->_set_error_message('email_failed_smtp_login', $reply);
1783 $this->_send_data(base64_encode($this->smtp_user));
1785 $reply = $this->_get_smtp_data();
1787 if (strncmp($reply, '334', 3) != 0)
1789 $this->_set_error_message('email_smtp_auth_un', $reply);
1793 $this->_send_data(base64_encode($this->smtp_pass));
1795 $reply = $this->_get_smtp_data();
1797 if (strncmp($reply, '235', 3) != 0)
1799 $this->_set_error_message('email_smtp_auth_pw', $reply);
1806 // --------------------------------------------------------------------
1814 private function _send_data($data)
1816 if ( ! fwrite($this->_smtp_connect, $data . $this->newline))
1818 $this->_set_error_message('email_smtp_data_failure', $data);
1827 // --------------------------------------------------------------------
1835 private function _get_smtp_data()
1839 while ($str = fgets($this->_smtp_connect, 512))
1843 if (substr($str, 3, 1) == " ")
1852 // --------------------------------------------------------------------
1860 private function _get_hostname()
1862 return (isset($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain';
1865 // --------------------------------------------------------------------
1873 private function _get_ip()
1875 if ($this->_IP !== FALSE)
1880 $cip = (isset($_SERVER['HTTP_CLIENT_IP']) AND $_SERVER['HTTP_CLIENT_IP'] != "") ? $_SERVER['HTTP_CLIENT_IP'] : FALSE;
1881 $rip = (isset($_SERVER['REMOTE_ADDR']) AND $_SERVER['REMOTE_ADDR'] != "") ? $_SERVER['REMOTE_ADDR'] : FALSE;
1882 $fip = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND $_SERVER['HTTP_X_FORWARDED_FOR'] != "") ? $_SERVER['HTTP_X_FORWARDED_FOR'] : FALSE;
1884 if ($cip && $rip) $this->_IP = $cip;
1885 elseif ($rip) $this->_IP = $rip;
1886 elseif ($cip) $this->_IP = $cip;
1887 elseif ($fip) $this->_IP = $fip;
1889 if (strpos($this->_IP, ',') !== FALSE)
1891 $x = explode(',', $this->_IP);
1892 $this->_IP = end($x);
1895 if ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $this->_IP))
1897 $this->_IP = '0.0.0.0';
1907 // --------------------------------------------------------------------
1915 public function print_debugger()
1919 if (count($this->_debug_msg) > 0)
1921 foreach ($this->_debug_msg as $val)
1927 $msg .= "<pre>".$this->_header_str."\n".htmlspecialchars($this->_subject)."\n".htmlspecialchars($this->_finalbody).'</pre>';
1931 // --------------------------------------------------------------------
1940 private function _set_error_message($msg, $val = '')
1942 $CI =& get_instance();
1943 $CI->lang->load('email');
1945 if (FALSE === ($line = $CI->lang->line($msg)))
1947 $this->_debug_msg[] = str_replace('%s', $val, $msg)."<br />";
1951 $this->_debug_msg[] = str_replace('%s', $val, $line)."<br />";
1955 // --------------------------------------------------------------------
1964 private function _mime_types($ext = "")
1966 $mimes = array( 'hqx' => 'application/mac-binhex40',
1967 'cpt' => 'application/mac-compactpro',
1968 'doc' => 'application/msword',
1969 'bin' => 'application/macbinary',
1970 'dms' => 'application/octet-stream',
1971 'lha' => 'application/octet-stream',
1972 'lzh' => 'application/octet-stream',
1973 'exe' => 'application/octet-stream',
1974 'class' => 'application/octet-stream',
1975 'psd' => 'application/octet-stream',
1976 'so' => 'application/octet-stream',
1977 'sea' => 'application/octet-stream',
1978 'dll' => 'application/octet-stream',
1979 'oda' => 'application/oda',
1980 'pdf' => 'application/pdf',
1981 'ai' => 'application/postscript',
1982 'eps' => 'application/postscript',
1983 'ps' => 'application/postscript',
1984 'smi' => 'application/smil',
1985 'smil' => 'application/smil',
1986 'mif' => 'application/vnd.mif',
1987 'xls' => 'application/vnd.ms-excel',
1988 'ppt' => 'application/vnd.ms-powerpoint',
1989 'wbxml' => 'application/vnd.wap.wbxml',
1990 'wmlc' => 'application/vnd.wap.wmlc',
1991 'dcr' => 'application/x-director',
1992 'dir' => 'application/x-director',
1993 'dxr' => 'application/x-director',
1994 'dvi' => 'application/x-dvi',
1995 'gtar' => 'application/x-gtar',
1996 'php' => 'application/x-httpd-php',
1997 'php4' => 'application/x-httpd-php',
1998 'php3' => 'application/x-httpd-php',
1999 'phtml' => 'application/x-httpd-php',
2000 'phps' => 'application/x-httpd-php-source',
2001 'js' => 'application/x-javascript',
2002 'swf' => 'application/x-shockwave-flash',
2003 'sit' => 'application/x-stuffit',
2004 'tar' => 'application/x-tar',
2005 'tgz' => 'application/x-tar',
2006 'xhtml' => 'application/xhtml+xml',
2007 'xht' => 'application/xhtml+xml',
2008 'zip' => 'application/zip',
2009 'mid' => 'audio/midi',
2010 'midi' => 'audio/midi',
2011 'mpga' => 'audio/mpeg',
2012 'mp2' => 'audio/mpeg',
2013 'mp3' => 'audio/mpeg',
2014 'aif' => 'audio/x-aiff',
2015 'aiff' => 'audio/x-aiff',
2016 'aifc' => 'audio/x-aiff',
2017 'ram' => 'audio/x-pn-realaudio',
2018 'rm' => 'audio/x-pn-realaudio',
2019 'rpm' => 'audio/x-pn-realaudio-plugin',
2020 'ra' => 'audio/x-realaudio',
2021 'rv' => 'video/vnd.rn-realvideo',
2022 'wav' => 'audio/x-wav',
2023 'bmp' => 'image/bmp',
2024 'gif' => 'image/gif',
2025 'jpeg' => 'image/jpeg',
2026 'jpg' => 'image/jpeg',
2027 'jpe' => 'image/jpeg',
2028 'png' => 'image/png',
2029 'tiff' => 'image/tiff',
2030 'tif' => 'image/tiff',
2031 'css' => 'text/css',
2032 'html' => 'text/html',
2033 'htm' => 'text/html',
2034 'shtml' => 'text/html',
2035 'txt' => 'text/plain',
2036 'text' => 'text/plain',
2037 'log' => 'text/plain',
2038 'rtx' => 'text/richtext',
2039 'rtf' => 'text/rtf',
2040 'xml' => 'text/xml',
2041 'xsl' => 'text/xml',
2042 'mpeg' => 'video/mpeg',
2043 'mpg' => 'video/mpeg',
2044 'mpe' => 'video/mpeg',
2045 'qt' => 'video/quicktime',
2046 'mov' => 'video/quicktime',
2047 'avi' => 'video/x-msvideo',
2048 'movie' => 'video/x-sgi-movie',
2049 'doc' => 'application/msword',
2050 'word' => 'application/msword',
2051 'xl' => 'application/excel',
2052 'eml' => 'message/rfc822'
2055 return ( ! isset($mimes[strtolower($ext)])) ? "application/x-unknown-content-type" : $mimes[strtolower($ext)];
2059 // END CI_Email class
2061 /* End of file Email.php */
2062 /* Location: ./system/libraries/Email.php */