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, 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 if ($name != '' && strncmp($name, '"', 1) != 0)
187 $name = '"'.$name.'"';
190 $this->_set_header('From', $name.' <'.$from.'>');
191 $this->_set_header('Return-Path', '<'.$from.'>');
194 // --------------------------------------------------------------------
204 function reply_to($replyto, $name = '')
206 if (preg_match( '/\<(.*)\>/', $replyto, $match))
208 $replyto = $match['1'];
213 $this->validate_email($this->_str_to_array($replyto));
221 if (strncmp($name, '"', 1) != 0)
223 $name = '"'.$name.'"';
226 $this->_set_header('Reply-To', $name.' <'.$replyto.'>');
227 $this->_replyto_flag = TRUE;
230 // --------------------------------------------------------------------
241 $to = $this->_str_to_array($to);
242 $to = $this->clean_email($to);
246 $this->validate_email($to);
249 if ($this->_get_protocol() != 'mail')
251 $this->_set_header('To', implode(", ", $to));
254 switch ($this->_get_protocol())
256 case 'smtp' : $this->_recipients = $to;
258 case 'sendmail' : $this->_recipients = implode(", ", $to);
260 case 'mail' : $this->_recipients = implode(", ", $to);
265 // --------------------------------------------------------------------
276 $cc = $this->_str_to_array($cc);
277 $cc = $this->clean_email($cc);
281 $this->validate_email($cc);
284 $this->_set_header('Cc', implode(", ", $cc));
286 if ($this->_get_protocol() == "smtp")
288 $this->_cc_array = $cc;
292 // --------------------------------------------------------------------
302 function bcc($bcc, $limit = '')
304 if ($limit != '' && is_numeric($limit))
306 $this->bcc_batch_mode = TRUE;
307 $this->bcc_batch_size = $limit;
310 $bcc = $this->_str_to_array($bcc);
311 $bcc = $this->clean_email($bcc);
315 $this->validate_email($bcc);
318 if (($this->_get_protocol() == "smtp") OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
320 $this->_bcc_array = $bcc;
324 $this->_set_header('Bcc', implode(", ", $bcc));
328 // --------------------------------------------------------------------
337 function subject($subject)
339 if (strpos($subject, "\r") !== FALSE OR strpos($subject, "\n") !== FALSE)
341 $subject = str_replace(array("\r\n", "\r", "\n"), '', $subject);
344 if (strpos($subject, "\t"))
346 $subject = str_replace("\t", ' ', $subject);
349 $this->_set_header('Subject', trim($subject));
352 // --------------------------------------------------------------------
361 function message($body)
363 $this->_body = stripslashes(rtrim(str_replace("\r", "", $body)));
366 // --------------------------------------------------------------------
369 * Assign file attachments
375 function attach($filename, $disposition = 'attachment')
377 $this->_attach_name[] = $filename;
378 $this->_attach_type[] = $this->_mime_types(next(explode('.', basename($filename))));
379 $this->_attach_disp[] = $disposition; // Can also be 'inline' Not sure if it matters
382 // --------------------------------------------------------------------
392 function _set_header($header, $value)
394 $this->_headers[$header] = $value;
397 // --------------------------------------------------------------------
400 * Convert a String to an Array
406 function _str_to_array($email)
408 if ( ! is_array($email))
410 if (strpos($email, ',') !== FALSE)
412 $email = preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY);
416 $email = trim($email);
417 settype($email, "array");
423 // --------------------------------------------------------------------
426 * Set Multipart Value
432 function set_alt_message($str = '')
434 $this->alt_message = ($str == '') ? '' : $str;
437 // --------------------------------------------------------------------
446 function set_mailtype($type = 'text')
448 $this->mailtype = ($type == 'html') ? 'html' : 'text';
451 // --------------------------------------------------------------------
460 function set_wordwrap($wordwrap = TRUE)
462 $this->wordwrap = ($wordwrap === FALSE) ? FALSE : TRUE;
465 // --------------------------------------------------------------------
474 function set_protocol($protocol = 'mail')
476 $this->protocol = ( ! in_array($protocol, $this->_protocols, TRUE)) ? 'mail' : strtolower($protocol);
479 // --------------------------------------------------------------------
488 function set_priority($n = 3)
490 if ( ! is_numeric($n))
496 if ($n < 1 OR $n > 5)
502 $this->priority = $n;
505 // --------------------------------------------------------------------
508 * Set Newline Character
514 function set_newline($newline = "\n")
516 if ($newline != "\n" AND $newline != "\r\n" AND $newline != "\r")
518 $this->newline = "\n";
522 $this->newline = $newline;
525 // --------------------------------------------------------------------
534 function set_crlf($crlf = "\n")
536 if ($crlf != "\n" AND $crlf != "\r\n" AND $crlf != "\r")
545 // --------------------------------------------------------------------
548 * Set Message Boundary
553 function _set_boundaries()
555 $this->_alt_boundary = "B_ALT_".uniqid(''); // multipart/alternative
556 $this->_atc_boundary = "B_ATC_".uniqid(''); // attachment boundary
559 // --------------------------------------------------------------------
567 function _get_message_id()
569 $from = $this->_headers['Return-Path'];
570 $from = str_replace(">", "", $from);
571 $from = str_replace("<", "", $from);
573 return "<".uniqid('').strstr($from, '@').">";
576 // --------------------------------------------------------------------
585 function _get_protocol($return = TRUE)
587 $this->protocol = strtolower($this->protocol);
588 $this->protocol = ( ! in_array($this->protocol, $this->_protocols, TRUE)) ? 'mail' : $this->protocol;
592 return $this->protocol;
596 // --------------------------------------------------------------------
605 function _get_encoding($return = TRUE)
607 $this->_encoding = ( ! in_array($this->_encoding, $this->_bit_depths)) ? '8bit' : $this->_encoding;
609 foreach ($this->_base_charsets as $charset)
611 if (strncmp($charset, $this->charset, strlen($charset)) == 0)
613 $this->_encoding = '7bit';
619 return $this->_encoding;
623 // --------------------------------------------------------------------
626 * Get content type (text/html/attachment)
631 function _get_content_type()
633 if ($this->mailtype == 'html' && count($this->_attach_name) == 0)
637 elseif ($this->mailtype == 'html' && count($this->_attach_name) > 0)
639 return 'html-attach';
641 elseif ($this->mailtype == 'text' && count($this->_attach_name) > 0)
643 return 'plain-attach';
651 // --------------------------------------------------------------------
661 $timezone = date("Z");
662 $operator = (strncmp($timezone, '-', 1) == 0) ? '-' : '+';
663 $timezone = abs($timezone);
664 $timezone = floor($timezone/3600) * 100 + ($timezone % 3600 ) / 60;
666 return sprintf("%s %s%04d", date("D, j M Y H:i:s"), $operator, $timezone);
669 // --------------------------------------------------------------------
677 function _get_mime_message()
679 return "This is a multi-part message in MIME format.".$this->newline."Your email application may not support this format.";
682 // --------------------------------------------------------------------
685 * Validate Email Address
691 function validate_email($email)
693 if ( ! is_array($email))
695 $this->_set_error_message('email_must_be_array');
699 foreach ($email as $val)
701 if ( ! $this->valid_email($val))
703 $this->_set_error_message('email_invalid_address', $val);
709 // --------------------------------------------------------------------
718 function valid_email($address)
720 return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
723 // --------------------------------------------------------------------
726 * Clean Extended Email Address: Joe Smith <joe@smith.com>
732 function clean_email($email)
734 if ( ! is_array($email))
736 if (preg_match('/\<(.*)\>/', $email, $match))
746 $clean_email = array();
748 foreach ($email as $addy)
750 if (preg_match( '/\<(.*)\>/', $addy, $match))
752 $clean_email[] = $match['1'];
756 $clean_email[] = $addy;
763 // --------------------------------------------------------------------
766 * Build alternative plain text message
768 * This function provides the raw message for use
769 * in plain-text headers of HTML-formatted emails.
770 * If the user hasn't specified his own alternative message
771 * it creates one by stripping the HTML
776 function _get_alt_message()
778 if ($this->alt_message != "")
780 return $this->word_wrap($this->alt_message, '76');
783 if (preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match))
789 $body = $this->_body;
792 $body = trim(strip_tags($body));
793 $body = preg_replace( '#<!--(.*)--\>#', "", $body);
794 $body = str_replace("\t", "", $body);
796 for ($i = 20; $i >= 3; $i--)
800 for ($x = 1; $x <= $i; $x ++)
805 $body = str_replace($n, "\n\n", $body);
808 return $this->word_wrap($body, '76');
811 // --------------------------------------------------------------------
821 function word_wrap($str, $charlim = '')
823 // Se the character limit
826 $charlim = ($this->wrapchars == "") ? "76" : $this->wrapchars;
829 // Reduce multiple spaces
830 $str = preg_replace("| +|", " ", $str);
832 // Standardize newlines
833 if (strpos($str, "\r") !== FALSE)
835 $str = str_replace(array("\r\n", "\r"), "\n", $str);
838 // If the current word is surrounded by {unwrap} tags we'll
839 // strip the entire chunk and replace it with a marker.
841 if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches))
843 for ($i = 0; $i < count($matches['0']); $i++)
845 $unwrap[] = $matches['1'][$i];
846 $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str);
850 // Use PHP's native function to do the initial wordwrap.
851 // We set the cut flag to FALSE so that any individual words that are
852 // too long get left alone. In the next step we'll deal with them.
853 $str = wordwrap($str, $charlim, "\n", FALSE);
855 // Split the string into individual lines of text and cycle through them
857 foreach (explode("\n", $str) as $line)
859 // Is the line within the allowed character count?
860 // If so we'll join it to the output and continue
861 if (strlen($line) <= $charlim)
863 $output .= $line.$this->newline;
868 while((strlen($line)) > $charlim)
870 // If the over-length word is a URL we won't wrap it
871 if (preg_match("!\[url.+\]|://|wwww.!", $line))
876 // Trim the word down
877 $temp .= substr($line, 0, $charlim-1);
878 $line = substr($line, $charlim-1);
881 // If $temp contains data it means we had to split up an over-length
882 // word into smaller chunks so we'll add it back to our current line
885 $output .= $temp.$this->newline.$line;
892 $output .= $this->newline;
895 // Put our markers back
896 if (count($unwrap) > 0)
898 foreach ($unwrap as $key => $val)
900 $output = str_replace("{{unwrapped".$key."}}", $val, $output);
907 // --------------------------------------------------------------------
910 * Build final headers
916 function _build_headers()
918 $this->_set_header('X-Sender', $this->clean_email($this->_headers['From']));
919 $this->_set_header('X-Mailer', $this->useragent);
920 $this->_set_header('X-Priority', $this->_priorities[$this->priority - 1]);
921 $this->_set_header('Message-ID', $this->_get_message_id());
922 $this->_set_header('Mime-Version', '1.0');
925 // --------------------------------------------------------------------
928 * Write Headers as a string
933 function _write_headers()
935 if ($this->protocol == 'mail')
937 $this->_subject = $this->_headers['Subject'];
938 unset($this->_headers['Subject']);
941 reset($this->_headers);
942 $this->_header_str = "";
944 foreach($this->_headers as $key => $val)
950 $this->_header_str .= $key.": ".$val.$this->newline;
954 if ($this->_get_protocol() == 'mail')
956 $this->_header_str = substr($this->_header_str, 0, -1);
960 // --------------------------------------------------------------------
963 * Build Final Body and attachments
968 function _build_message()
970 if ($this->wordwrap === TRUE AND $this->mailtype != 'html')
972 $this->_body = $this->word_wrap($this->_body);
975 $this->_set_boundaries();
976 $this->_write_headers();
978 $hdr = ($this->_get_protocol() == 'mail') ? $this->newline : '';
980 switch ($this->_get_content_type())
984 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
985 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();
987 if ($this->_get_protocol() == 'mail')
989 $this->_header_str .= $hdr;
990 $this->_finalbody = $this->_body;
995 $hdr .= $this->newline . $this->newline . $this->_body;
997 $this->_finalbody = $hdr;
1003 if ($this->send_multipart === FALSE)
1005 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1006 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1010 $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline;
1011 $hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
1012 $hdr .= "--" . $this->_alt_boundary . $this->newline;
1014 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1015 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
1016 $hdr .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
1018 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1019 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1022 $this->_body = $this->_prep_quoted_printable($this->_body);
1024 if ($this->_get_protocol() == 'mail')
1026 $this->_header_str .= $hdr;
1027 $this->_finalbody = $this->_body . $this->newline . $this->newline;
1029 if ($this->send_multipart !== FALSE)
1031 $this->_finalbody .= "--" . $this->_alt_boundary . "--";
1037 $hdr .= $this->newline . $this->newline;
1038 $hdr .= $this->_body . $this->newline . $this->newline;
1040 if ($this->send_multipart !== FALSE)
1042 $hdr .= "--" . $this->_alt_boundary . "--";
1045 $this->_finalbody = $hdr;
1049 case 'plain-attach' :
1051 $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline;
1052 $hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
1053 $hdr .= "--" . $this->_atc_boundary . $this->newline;
1055 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1056 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();
1058 if ($this->_get_protocol() == 'mail')
1060 $this->_header_str .= $hdr;
1062 $body = $this->_body . $this->newline . $this->newline;
1065 $hdr .= $this->newline . $this->newline;
1066 $hdr .= $this->_body . $this->newline . $this->newline;
1069 case 'html-attach' :
1071 $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline;
1072 $hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
1073 $hdr .= "--" . $this->_atc_boundary . $this->newline;
1075 $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline .$this->newline;
1076 $hdr .= "--" . $this->_alt_boundary . $this->newline;
1078 $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
1079 $hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
1080 $hdr .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
1082 $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
1083 $hdr .= "Content-Transfer-Encoding: quoted-printable";
1085 $this->_body = $this->_prep_quoted_printable($this->_body);
1087 if ($this->_get_protocol() == 'mail')
1089 $this->_header_str .= $hdr;
1091 $body = $this->_body . $this->newline . $this->newline;
1092 $body .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;
1095 $hdr .= $this->newline . $this->newline;
1096 $hdr .= $this->_body . $this->newline . $this->newline;
1097 $hdr .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;
1102 $attachment = array();
1106 for ($i=0; $i < count($this->_attach_name); $i++)
1108 $filename = $this->_attach_name[$i];
1109 $basename = basename($filename);
1110 $ctype = $this->_attach_type[$i];
1112 if ( ! file_exists($filename))
1114 $this->_set_error_message('email_attachment_missing', $filename);
1118 $h = "--".$this->_atc_boundary.$this->newline;
1119 $h .= "Content-type: ".$ctype."; ";
1120 $h .= "name=\"".$basename."\"".$this->newline;
1121 $h .= "Content-Disposition: ".$this->_attach_disp[$i].";".$this->newline;
1122 $h .= "Content-Transfer-Encoding: base64".$this->newline;
1124 $attachment[$z++] = $h;
1125 $file = filesize($filename) +1;
1127 if ( ! $fp = fopen($filename, FOPEN_READ))
1129 $this->_set_error_message('email_attachment_unreadable', $filename);
1133 $attachment[$z++] = chunk_split(base64_encode(fread($fp, $file)));
1137 if ($this->_get_protocol() == 'mail')
1139 $this->_finalbody = $body . implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";
1144 $this->_finalbody = $hdr.implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";
1149 // --------------------------------------------------------------------
1152 * Prep Quoted Printable
1154 * Prepares string for Quoted-Printable Content-Transfer-Encoding
1155 * Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt
1162 function _prep_quoted_printable($str, $charlim = '')
1164 // Set the character limit
1165 // Don't allow over 76, as that will make servers and MUAs barf
1166 // all over quoted-printable data
1167 if ($charlim == '' OR $charlim > '76')
1172 // Reduce multiple spaces
1173 $str = preg_replace("| +|", " ", $str);
1176 $str = preg_replace('/\x00+/', '', $str);
1178 // Standardize newlines
1179 if (strpos($str, "\r") !== FALSE)
1181 $str = str_replace(array("\r\n", "\r"), "\n", $str);
1184 // We are intentionally wrapping so mail servers will encode characters
1185 // properly and MUAs will behave, so {unwrap} must go!
1186 $str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str);
1188 // Break into an array of lines
1189 $lines = explode("\n", $str);
1194 foreach ($lines as $line)
1196 $length = strlen($line);
1199 // Loop through each character in the line to add soft-wrap
1200 // characters at the end of a line " =\r\n" and add the newly
1201 // processed line(s) to the output (see comment on $crlf class property)
1202 for ($i = 0; $i < $length; $i++)
1204 // Grab the next character
1205 $char = substr($line, $i, 1);
1206 $ascii = ord($char);
1208 // Convert spaces and tabs but only if it's the end of the line
1209 if ($i == ($length - 1))
1211 $char = ($ascii == '32' OR $ascii == '9') ? $escape.sprintf('%02s', dechex($ascii)) : $char;
1217 $char = $escape.strtoupper(sprintf('%02s', dechex($ascii))); // =3D
1220 // If we're at the character limit, add the line to the output,
1221 // reset our temp variable, and keep on chuggin'
1222 if ((strlen($temp) + strlen($char)) >= $charlim)
1224 $output .= $temp.$escape.$this->crlf;
1228 // Add the character to our temporary line
1232 // Add our completed line to the output
1233 $output .= $temp.$this->crlf;
1236 // get rid of extra CRLF tacked onto the end
1237 $output = substr($output, 0, strlen($this->crlf) * -1);
1242 // --------------------------------------------------------------------
1252 if ($this->_replyto_flag == FALSE)
1254 $this->reply_to($this->_headers['From']);
1257 if (( ! isset($this->_recipients) AND ! isset($this->_headers['To'])) AND
1258 ( ! isset($this->_bcc_array) AND ! isset($this->_headers['Bcc'])) AND
1259 ( ! isset($this->_headers['Cc'])))
1261 $this->_set_error_message('email_no_recipients');
1265 $this->_build_headers();
1267 if ($this->bcc_batch_mode AND count($this->_bcc_array) > 0)
1269 if (count($this->_bcc_array) > $this->bcc_batch_size)
1270 return $this->batch_bcc_send();
1273 $this->_build_message();
1275 if ( ! $this->_spool_email())
1285 // --------------------------------------------------------------------
1288 * Batch Bcc Send. Sends groups of BCCs in batches
1293 function batch_bcc_send()
1295 $float = $this->bcc_batch_size -1;
1301 for ($i = 0; $i < count($this->_bcc_array); $i++)
1303 if (isset($this->_bcc_array[$i]))
1305 $set .= ", ".$this->_bcc_array[$i];
1310 $chunk[] = substr($set, 1);
1311 $float = $float + $this->bcc_batch_size;
1315 if ($i == count($this->_bcc_array)-1)
1317 $chunk[] = substr($set, 1);
1321 for ($i = 0; $i < count($chunk); $i++)
1323 unset($this->_headers['Bcc']);
1326 $bcc = $this->_str_to_array($chunk[$i]);
1327 $bcc = $this->clean_email($bcc);
1329 if ($this->protocol != 'smtp')
1331 $this->_set_header('Bcc', implode(", ", $bcc));
1335 $this->_bcc_array = $bcc;
1338 $this->_build_message();
1339 $this->_spool_email();
1343 // --------------------------------------------------------------------
1346 * Unwrap special elements
1351 function _unwrap_specials()
1353 $this->_finalbody = preg_replace_callback("/\{unwrap\}(.*?)\{\/unwrap\}/si", array($this, '_remove_nl_callback'), $this->_finalbody);
1356 // --------------------------------------------------------------------
1359 * Strip line-breaks via callback
1364 function _remove_nl_callback($matches)
1366 if (strpos($matches[1], "\r") !== FALSE OR strpos($matches[1], "\n") !== FALSE)
1368 $matches[1] = str_replace(array("\r\n", "\r", "\n"), '', $matches[1]);
1374 // --------------------------------------------------------------------
1377 * Spool mail to the mail server
1382 function _spool_email()
1384 $this->_unwrap_specials();
1386 switch ($this->_get_protocol())
1390 if ( ! $this->_send_with_mail())
1392 $this->_set_error_message('email_send_failure_phpmail');
1398 if ( ! $this->_send_with_sendmail())
1400 $this->_set_error_message('email_send_failure_sendmail');
1406 if ( ! $this->_send_with_smtp())
1408 $this->_set_error_message('email_send_failure_smtp');
1415 $this->_set_error_message('email_sent', $this->_get_protocol());
1419 // --------------------------------------------------------------------
1427 function _send_with_mail()
1429 if ($this->_safe_mode == TRUE)
1431 if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str))
1442 // most documentation of sendmail using the "-f" flag lacks a space after it, however
1443 // we've encountered servers that seem to require it to be in place.
1444 if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, "-f ".$this->clean_email($this->_headers['From'])))
1455 // --------------------------------------------------------------------
1458 * Send using Sendmail
1463 function _send_with_sendmail()
1465 $fp = @popen($this->mailpath . " -oi -f ".$this->clean_email($this->_headers['From'])." -t", 'w');
1467 if ( ! is_resource($fp))
1469 $this->_set_error_message('email_no_socket');
1473 fputs($fp, $this->_header_str);
1474 fputs($fp, $this->_finalbody);
1475 pclose($fp) >> 8 & 0xFF;
1480 // --------------------------------------------------------------------
1488 function _send_with_smtp()
1490 if ($this->smtp_host == '')
1492 $this->_set_error_message('email_no_hostname');
1496 $this->_smtp_connect();
1497 $this->_smtp_authenticate();
1499 $this->_send_command('from', $this->clean_email($this->_headers['From']));
1501 foreach($this->_recipients as $val)
1503 $this->_send_command('to', $val);
1506 if (count($this->_cc_array) > 0)
1508 foreach($this->_cc_array as $val)
1512 $this->_send_command('to', $val);
1517 if (count($this->_bcc_array) > 0)
1519 foreach($this->_bcc_array as $val)
1523 $this->_send_command('to', $val);
1528 $this->_send_command('data');
1530 // perform dot transformation on any lines that begin with a dot
1531 $this->_send_data($this->_header_str . preg_replace('/^\./m', '..$1', $this->_finalbody));
1533 $this->_send_data('.');
1535 $reply = $this->_get_smtp_data();
1537 $this->_set_error_message($reply);
1539 if (strncmp($reply, '250', 3) != 0)
1541 $this->_set_error_message('email_smtp_error', $reply);
1545 $this->_send_command('quit');
1549 // --------------------------------------------------------------------
1558 function _smtp_connect()
1560 $this->_smtp_connect = fsockopen($this->smtp_host,
1564 $this->smtp_timeout);
1566 if( ! is_resource($this->_smtp_connect))
1568 $this->_set_error_message('email_smtp_error', $errno." ".$errstr);
1572 $this->_set_error_message($this->_get_smtp_data());
1573 return $this->_send_command('hello');
1576 // --------------------------------------------------------------------
1586 function _send_command($cmd, $data = '')
1592 if ($this->_smtp_auth OR $this->_get_encoding() == '8bit')
1593 $this->_send_data('EHLO '.$this->_get_hostname());
1595 $this->_send_data('HELO '.$this->_get_hostname());
1601 $this->_send_data('MAIL FROM:<'.$data.'>');
1607 $this->_send_data('RCPT TO:<'.$data.'>');
1613 $this->_send_data('DATA');
1619 $this->_send_data('QUIT');
1625 $reply = $this->_get_smtp_data();
1627 $this->_debug_msg[] = "<pre>".$cmd.": ".$reply."</pre>";
1629 if (substr($reply, 0, 3) != $resp)
1631 $this->_set_error_message('email_smtp_error', $reply);
1637 fclose($this->_smtp_connect);
1643 // --------------------------------------------------------------------
1651 function _smtp_authenticate()
1653 if ( ! $this->_smtp_auth)
1658 if ($this->smtp_user == "" AND $this->smtp_pass == "")
1660 $this->_set_error_message('email_no_smtp_unpw');
1664 $this->_send_data('AUTH LOGIN');
1666 $reply = $this->_get_smtp_data();
1668 if (strncmp($reply, '334', 3) != 0)
1670 $this->_set_error_message('email_failed_smtp_login', $reply);
1674 $this->_send_data(base64_encode($this->smtp_user));
1676 $reply = $this->_get_smtp_data();
1678 if (strncmp($reply, '334', 3) != 0)
1680 $this->_set_error_message('email_smtp_auth_un', $reply);
1684 $this->_send_data(base64_encode($this->smtp_pass));
1686 $reply = $this->_get_smtp_data();
1688 if (strncmp($reply, '235', 3) != 0)
1690 $this->_set_error_message('email_smtp_auth_pw', $reply);
1697 // --------------------------------------------------------------------
1705 function _send_data($data)
1707 if ( ! fwrite($this->_smtp_connect, $data . $this->newline))
1709 $this->_set_error_message('email_smtp_data_failure', $data);
1718 // --------------------------------------------------------------------
1726 function _get_smtp_data()
1730 while ($str = fgets($this->_smtp_connect, 512))
1734 if (substr($str, 3, 1) == " ")
1743 // --------------------------------------------------------------------
1751 function _get_hostname()
1753 return (isset($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain';
1756 // --------------------------------------------------------------------
1766 if ($this->_IP !== FALSE)
1771 $cip = (isset($_SERVER['HTTP_CLIENT_IP']) AND $_SERVER['HTTP_CLIENT_IP'] != "") ? $_SERVER['HTTP_CLIENT_IP'] : FALSE;
1772 $rip = (isset($_SERVER['REMOTE_ADDR']) AND $_SERVER['REMOTE_ADDR'] != "") ? $_SERVER['REMOTE_ADDR'] : FALSE;
1773 $fip = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND $_SERVER['HTTP_X_FORWARDED_FOR'] != "") ? $_SERVER['HTTP_X_FORWARDED_FOR'] : FALSE;
1775 if ($cip && $rip) $this->_IP = $cip;
1776 elseif ($rip) $this->_IP = $rip;
1777 elseif ($cip) $this->_IP = $cip;
1778 elseif ($fip) $this->_IP = $fip;
1780 if (strstr($this->_IP, ','))
1782 $x = explode(',', $this->_IP);
1783 $this->_IP = end($x);
1786 if ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $this->_IP))
1788 $this->_IP = '0.0.0.0';
1798 // --------------------------------------------------------------------
1806 function print_debugger()
1810 if (count($this->_debug_msg) > 0)
1812 foreach ($this->_debug_msg as $val)
1818 $msg .= "<pre>".$this->_header_str."\n".htmlspecialchars($this->_subject)."\n".htmlspecialchars($this->_finalbody).'</pre>';
1822 // --------------------------------------------------------------------
1831 function _set_error_message($msg, $val = '')
1833 $CI =& get_instance();
1834 $CI->lang->load('email');
1836 if (FALSE === ($line = $CI->lang->line($msg)))
1838 $this->_debug_msg[] = str_replace('%s', $val, $msg)."<br />";
1842 $this->_debug_msg[] = str_replace('%s', $val, $line)."<br />";
1846 // --------------------------------------------------------------------
1855 function _mime_types($ext = "")
1857 $mimes = array( 'hqx' => 'application/mac-binhex40',
1858 'cpt' => 'application/mac-compactpro',
1859 'doc' => 'application/msword',
1860 'bin' => 'application/macbinary',
1861 'dms' => 'application/octet-stream',
1862 'lha' => 'application/octet-stream',
1863 'lzh' => 'application/octet-stream',
1864 'exe' => 'application/octet-stream',
1865 'class' => 'application/octet-stream',
1866 'psd' => 'application/octet-stream',
1867 'so' => 'application/octet-stream',
1868 'sea' => 'application/octet-stream',
1869 'dll' => 'application/octet-stream',
1870 'oda' => 'application/oda',
1871 'pdf' => 'application/pdf',
1872 'ai' => 'application/postscript',
1873 'eps' => 'application/postscript',
1874 'ps' => 'application/postscript',
1875 'smi' => 'application/smil',
1876 'smil' => 'application/smil',
1877 'mif' => 'application/vnd.mif',
1878 'xls' => 'application/vnd.ms-excel',
1879 'ppt' => 'application/vnd.ms-powerpoint',
1880 'wbxml' => 'application/vnd.wap.wbxml',
1881 'wmlc' => 'application/vnd.wap.wmlc',
1882 'dcr' => 'application/x-director',
1883 'dir' => 'application/x-director',
1884 'dxr' => 'application/x-director',
1885 'dvi' => 'application/x-dvi',
1886 'gtar' => 'application/x-gtar',
1887 'php' => 'application/x-httpd-php',
1888 'php4' => 'application/x-httpd-php',
1889 'php3' => 'application/x-httpd-php',
1890 'phtml' => 'application/x-httpd-php',
1891 'phps' => 'application/x-httpd-php-source',
1892 'js' => 'application/x-javascript',
1893 'swf' => 'application/x-shockwave-flash',
1894 'sit' => 'application/x-stuffit',
1895 'tar' => 'application/x-tar',
1896 'tgz' => 'application/x-tar',
1897 'xhtml' => 'application/xhtml+xml',
1898 'xht' => 'application/xhtml+xml',
1899 'zip' => 'application/zip',
1900 'mid' => 'audio/midi',
1901 'midi' => 'audio/midi',
1902 'mpga' => 'audio/mpeg',
1903 'mp2' => 'audio/mpeg',
1904 'mp3' => 'audio/mpeg',
1905 'aif' => 'audio/x-aiff',
1906 'aiff' => 'audio/x-aiff',
1907 'aifc' => 'audio/x-aiff',
1908 'ram' => 'audio/x-pn-realaudio',
1909 'rm' => 'audio/x-pn-realaudio',
1910 'rpm' => 'audio/x-pn-realaudio-plugin',
1911 'ra' => 'audio/x-realaudio',
1912 'rv' => 'video/vnd.rn-realvideo',
1913 'wav' => 'audio/x-wav',
1914 'bmp' => 'image/bmp',
1915 'gif' => 'image/gif',
1916 'jpeg' => 'image/jpeg',
1917 'jpg' => 'image/jpeg',
1918 'jpe' => 'image/jpeg',
1919 'png' => 'image/png',
1920 'tiff' => 'image/tiff',
1921 'tif' => 'image/tiff',
1922 'css' => 'text/css',
1923 'html' => 'text/html',
1924 'htm' => 'text/html',
1925 'shtml' => 'text/html',
1926 'txt' => 'text/plain',
1927 'text' => 'text/plain',
1928 'log' => 'text/plain',
1929 'rtx' => 'text/richtext',
1930 'rtf' => 'text/rtf',
1931 'xml' => 'text/xml',
1932 'xsl' => 'text/xml',
1933 'mpeg' => 'video/mpeg',
1934 'mpg' => 'video/mpeg',
1935 'mpe' => 'video/mpeg',
1936 'qt' => 'video/quicktime',
1937 'mov' => 'video/quicktime',
1938 'avi' => 'video/x-msvideo',
1939 'movie' => 'video/x-sgi-movie',
1940 'doc' => 'application/msword',
1941 'word' => 'application/msword',
1942 'xl' => 'application/excel',
1943 'eml' => 'message/rfc822'
1946 return ( ! isset($mimes[strtolower($ext)])) ? "application/x-unknown-content-type" : $mimes[strtolower($ext)];
1950 // END CI_Email class
1952 /* End of file Email.php */
1953 /* Location: ./system/libraries/Email.php */