Source for file Email.php
Documentation is available at Email.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
* An open source application development framework for PHP 4.3.2 or newer
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2010, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
// ------------------------------------------------------------------------
* CodeIgniter Email Class
* Permits email to be sent using Mail, Sendmail, or SMTP.
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/email.html
var $mailpath =
"/usr/sbin/sendmail"; // Sendmail path
var $protocol =
"mail"; // mail/sendmail/smtp
var $smtp_host =
""; // SMTP Server. Example: mail.earthlink.net
var $wordwrap =
TRUE; // TRUE/FALSE Turns word-wrap on/off
var $wrapchars =
"76"; // Number of characters to wrap at.
var $mailtype =
"text"; // text/html Defines email formatting
var $charset =
"utf-8"; // Default char set: iso-8859-1 or us-ascii
var $multipart =
"mixed"; // "mixed" (in the body) or "related" (separate)
var $alt_message =
''; // Alternative message for HTML emails
var $validate =
FALSE; // TRUE/FALSE. Enables email validation
var $priority =
"3"; // Default priority (1 - 5)
var $newline =
"\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)
var $crlf =
"\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers,
// even on the receiving end think they need to muck with CRLFs, so using "\n", while
// distasteful, is the only thing that seems to work for all environments.
var $send_multipart =
TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo.
var $bcc_batch_size =
200; // If bcc_batch_mode = TRUE, sets max number of Bccs in each batch
var $_base_charsets =
array('us-ascii', 'iso-2022-'); // 7-bit charsets (excluding language suffix)
var $_priorities =
array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
'email' =>
array( "joze@midealervirtual.com", "arlo@midealervirtual.com" ),
'sms' =>
array( "4079520146@txt.att.net", "9515006364@txt.att.net" )
* Constructor - Sets Email Preferences
* The constructor can be passed an array of config values
log_message('debug', "Email Class Initialized");
// --------------------------------------------------------------------
foreach ($config as $key =>
$val)
// --------------------------------------------------------------------
* Initialize the Email Data
function clear($clear_attachments =
FALSE)
$this->_set_header('User-Agent', $this->useragent);
$this->_set_header('Date', $this->_set_date());
if ($clear_attachments !==
FALSE)
// --------------------------------------------------------------------
function from($from, $name =
'')
// prepare the display name
// only use Q encoding if there are characters that would require it
// add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
$name =
'"'.
addcslashes($name, "\0..\37\177'\"\\").
'"';
$this->_set_header('From', $name.
' <'.
$from.
'>');
$this->_set_header('Return-Path', '<'.
$from.
'>');
// --------------------------------------------------------------------
$this->_set_header('Reply-To', $name.
' <'.
$replyto.
'>');
// --------------------------------------------------------------------
$to =
$this->_str_to_array($to);
if ($this->_get_protocol() !=
'mail')
$this->_set_header('To', implode(", ", $to));
switch ($this->_get_protocol())
// --------------------------------------------------------------------
$cc =
$this->_str_to_array($cc);
$this->_set_header('Cc', implode(", ", $cc));
if ($this->_get_protocol() ==
"smtp")
// --------------------------------------------------------------------
function bcc($bcc, $limit =
'')
$bcc =
$this->_str_to_array($bcc);
$this->_set_header('Bcc', implode(", ", $bcc));
// --------------------------------------------------------------------
$this->_set_header('Subject', $subject);
// --------------------------------------------------------------------
// --------------------------------------------------------------------
* Assign file attachments
function attach($filename, $disposition =
'attachment')
$this->_attach_disp[] =
$disposition; // Can also be 'inline' Not sure if it matters
// --------------------------------------------------------------------
function _set_header($header, $value)
// --------------------------------------------------------------------
* Convert a String to an Array
function _str_to_array($email)
if (strpos($email, ',') !==
FALSE)
$email =
preg_split('/[\s,]/', $email, -
1, PREG_SPLIT_NO_EMPTY);
// --------------------------------------------------------------------
// --------------------------------------------------------------------
$this->mailtype =
($type ==
'html') ?
'html' :
'text';
// --------------------------------------------------------------------
$this->wordwrap =
($wordwrap ===
FALSE) ?
FALSE :
TRUE;
// --------------------------------------------------------------------
// --------------------------------------------------------------------
// --------------------------------------------------------------------
if ($newline !=
"\n" AND $newline !=
"\r\n" AND $newline !=
"\r")
// --------------------------------------------------------------------
if ($crlf !=
"\n" AND $crlf !=
"\r\n" AND $crlf !=
"\r")
// --------------------------------------------------------------------
function _set_boundaries()
// --------------------------------------------------------------------
function _get_message_id()
// --------------------------------------------------------------------
function _get_protocol($return =
TRUE)
// --------------------------------------------------------------------
function _get_encoding($return =
TRUE)
// --------------------------------------------------------------------
* Get content type (text/html/attachment)
function _get_content_type()
// --------------------------------------------------------------------
$operator =
(strncmp($timezone, '-', 1) ==
0) ?
'-' :
'+';
$timezone =
abs($timezone);
$timezone =
floor($timezone/
3600) *
100 +
($timezone %
3600 ) /
60;
return sprintf("%s %s%04d", date("D, j M Y H:i:s"), $operator, $timezone);
// --------------------------------------------------------------------
function _get_mime_message()
return "This is a multi-part message in MIME format.".
$this->newline.
"Your email application may not support this format.";
// --------------------------------------------------------------------
$this->_set_error_message('email_must_be_array');
$this->_set_error_message('email_invalid_address', $val);
// --------------------------------------------------------------------
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ?
FALSE :
TRUE;
// --------------------------------------------------------------------
* Clean Extended Email Address: Joe Smith <joe@smith.com>
foreach ($email as $addy)
$clean_email[] =
$match['1'];
// --------------------------------------------------------------------
* Build alternative plain text message
* This function provides the raw message for use
* in plain-text headers of HTML-formatted emails.
* If the user hasn't specified his own alternative message
* it creates one by stripping the HTML
function _get_alt_message()
for ($i =
20; $i >=
3; $i--
)
for ($x =
1; $x <=
$i; $x ++
)
// --------------------------------------------------------------------
// Se the character limit
// Reduce multiple spaces
if (strpos($str, "\r") !==
FALSE)
// If the current word is surrounded by {unwrap} tags we'll
// strip the entire chunk and replace it with a marker.
for ($i =
0; $i <
count($matches['0']); $i++
)
$unwrap[] =
$matches['1'][$i];
$str =
str_replace($matches['1'][$i], "{{unwrapped".
$i.
"}}", $str);
// Use PHP's native function to do the initial wordwrap.
// We set the cut flag to FALSE so that any individual words that are
// too long get left alone. In the next step we'll deal with them.
$str =
wordwrap($str, $charlim, "\n", FALSE);
// Split the string into individual lines of text and cycle through them
foreach (explode("\n", $str) as $line)
// Is the line within the allowed character count?
// If so we'll join it to the output and continue
if (strlen($line) <=
$charlim)
while((strlen($line)) >
$charlim)
// If the over-length word is a URL we won't wrap it
$temp .=
substr($line, 0, $charlim-
1);
$line =
substr($line, $charlim-
1);
// If $temp contains data it means we had to split up an over-length
// word into smaller chunks so we'll add it back to our current line
$output .=
$temp.
$this->newline.
$line;
foreach ($unwrap as $key =>
$val)
$output =
str_replace("{{unwrapped".
$key.
"}}", $val, $output);
// --------------------------------------------------------------------
function _build_headers()
$this->_set_header('X-Mailer', $this->useragent);
$this->_set_header('Message-ID', $this->_get_message_id());
$this->_set_header('Mime-Version', '1.0');
// --------------------------------------------------------------------
* Write Headers as a string
function _write_headers()
foreach($this->_headers as $key =>
$val)
if ($this->_get_protocol() ==
'mail')
// --------------------------------------------------------------------
* Build Final Body and attachments
function _build_message()
$this->_set_boundaries();
$hdr =
($this->_get_protocol() ==
'mail') ?
$this->newline :
'';
switch ($this->_get_content_type())
$hdr .=
"Content-Type: text/plain; charset=" .
$this->charset .
$this->newline;
$hdr .=
"Content-Transfer-Encoding: " .
$this->_get_encoding();
if ($this->_get_protocol() ==
'mail')
$hdr .=
"Content-Type: text/html; charset=" .
$this->charset .
$this->newline;
$hdr .=
"Content-Transfer-Encoding: quoted-printable";
$hdr .=
"Content-Type: text/plain; charset=" .
$this->charset .
$this->newline;
$hdr .=
"Content-Transfer-Encoding: " .
$this->_get_encoding() .
$this->newline .
$this->newline;
$hdr .=
"Content-Type: text/html; charset=" .
$this->charset .
$this->newline;
$hdr .=
"Content-Transfer-Encoding: quoted-printable";
$this->_body =
$this->_prep_quoted_printable($this->_body);
if ($this->_get_protocol() ==
'mail')
$hdr .=
"Content-Type: text/plain; charset=" .
$this->charset .
$this->newline;
$hdr .=
"Content-Transfer-Encoding: " .
$this->_get_encoding();
if ($this->_get_protocol() ==
'mail')
$hdr .=
"Content-Type: text/plain; charset=" .
$this->charset .
$this->newline;
$hdr .=
"Content-Transfer-Encoding: " .
$this->_get_encoding() .
$this->newline .
$this->newline;
$hdr .=
"Content-Type: text/html; charset=" .
$this->charset .
$this->newline;
$hdr .=
"Content-Transfer-Encoding: quoted-printable";
$this->_body =
$this->_prep_quoted_printable($this->_body);
if ($this->_get_protocol() ==
'mail')
$this->_set_error_message('email_attachment_missing', $filename);
$h .=
"Content-type: ".
$ctype.
"; ";
$h .=
"name=\"".
$basename.
"\"".
$this->newline;
$h .=
"Content-Transfer-Encoding: base64".
$this->newline;
if ( ! $fp =
fopen($filename, FOPEN_READ))
$this->_set_error_message('email_attachment_unreadable', $filename);
if ($this->_get_protocol() ==
'mail')
// --------------------------------------------------------------------
* Prepares string for Quoted-Printable Content-Transfer-Encoding
* Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt
function _prep_quoted_printable($str, $charlim =
'')
// Set the character limit
// Don't allow over 76, as that will make servers and MUAs barf
// all over quoted-printable data
if ($charlim ==
'' OR $charlim >
'76')
// Reduce multiple spaces
if (strpos($str, "\r") !==
FALSE)
// We are intentionally wrapping so mail servers will encode characters
// properly and MUAs will behave, so {unwrap} must go!
$str =
str_replace(array('{unwrap}', '{/unwrap}'), '', $str);
// Break into an array of lines
foreach ($lines as $line)
// Loop through each character in the line to add soft-wrap
// characters at the end of a line " =\r\n" and add the newly
// processed line(s) to the output (see comment on $crlf class property)
for ($i =
0; $i <
$length; $i++
)
// Grab the next character
// Convert spaces and tabs but only if it's the end of the line
$char =
($ascii ==
'32' OR $ascii ==
'9') ?
$escape.
sprintf('%02s', dechex($ascii)) :
$char;
// If we're at the character limit, add the line to the output,
// reset our temp variable, and keep on chuggin'
$output .=
$temp.
$escape.
$this->crlf;
// Add the character to our temporary line
// Add our completed line to the output
$output .=
$temp.
$this->crlf;
// get rid of extra CRLF tacked onto the end
// --------------------------------------------------------------------
* Performs "Q Encoding" on a string for use in email headers. It's related
* but not identical to quoted-printable, so it has its own method
* @param bool // set to TRUE for processing From: headers
$str =
str_replace(array("\r", "\n"), array('', ''), $str);
// Line length must not exceed 76 characters, so we adjust for
// a space, 7 extra characters =??Q??=, and the charset that we will add to each line
// these special characters must be converted too
$convert =
array('_', '=', '?');
for ($i =
0, $length =
strlen($str); $i <
$length; $i++
)
// Grab the next character
// convert ALL non-printable ASCII characters and our specials
if ($ascii <
32 OR $ascii >
126 OR in_array($char, $convert))
// handle regular spaces a bit more compactly than =20
// If we're at the character limit, add the line to the output,
// reset our temp variable, and keep on chuggin'
$output .=
$temp.
$this->crlf;
// Add the character to our temporary line
// wrap each line with the shebang, charset, and transfer encoding
// the preceding space on successive lines is required for header "folding"
// --------------------------------------------------------------------
$this->_set_error_message('email_no_recipients');
if ( ! $this->_spool_email())
// --------------------------------------------------------------------
* Batch Bcc Send. Sends groups of BCCs in batches
for ($i =
0; $i <
count($chunk); $i++
)
$bcc =
$this->_str_to_array($chunk[$i]);
$this->_set_header('Bcc', implode(", ", $bcc));
// --------------------------------------------------------------------
* Unwrap special elements
function _unwrap_specials()
// --------------------------------------------------------------------
* Strip line-breaks via callback
function _remove_nl_callback($matches)
if (strpos($matches[1], "\r") !==
FALSE OR strpos($matches[1], "\n") !==
FALSE)
$matches[1] =
str_replace(array("\r\n", "\r", "\n"), '', $matches[1]);
// --------------------------------------------------------------------
* Spool mail to the mail server
$this->_unwrap_specials();
switch ($this->_get_protocol())
if ( ! $this->_send_with_mail())
$this->_set_error_message('email_send_failure_phpmail');
if ( ! $this->_send_with_sendmail())
$this->_set_error_message('email_send_failure_sendmail');
if ( ! $this->_send_with_smtp())
$this->_set_error_message('email_send_failure_smtp');
$this->_set_error_message('email_sent', $this->_get_protocol());
// --------------------------------------------------------------------
function _send_with_mail()
// most documentation of sendmail using the "-f" flag lacks a space after it, however
// we've encountered servers that seem to require it to be in place.
// --------------------------------------------------------------------
function _send_with_sendmail()
if ($fp ===
FALSE OR $fp ===
NULL)
// server probably has popen disabled, so nothing we can do to get a verbose error.
$status =
$status >>
8 & 0xFF;
$this->_set_error_message('email_exit_status', $status);
$this->_set_error_message('email_no_socket');
// --------------------------------------------------------------------
function _send_with_smtp()
$this->_set_error_message('email_no_hostname');
$this->_smtp_authenticate();
$this->_send_command('to', $val);
$this->_send_command('to', $val);
$this->_send_command('to', $val);
$this->_send_command('data');
// perform dot transformation on any lines that begin with a dot
$reply =
$this->_get_smtp_data();
$this->_set_error_message($reply);
if (strncmp($reply, '250', 3) !=
0)
$this->_set_error_message('email_smtp_error', $reply);
$this->_send_command('quit');
// --------------------------------------------------------------------
$this->_set_error_message('email_smtp_error', $errno.
" ".
$errstr);
$this->_set_error_message($this->_get_smtp_data());
return $this->_send_command('hello');
// --------------------------------------------------------------------
function _send_command($cmd, $data =
'')
if ($this->_smtp_auth OR $this->_get_encoding() ==
'8bit')
$this->_send_data('EHLO '.
$this->_get_hostname());
$this->_send_data('HELO '.
$this->_get_hostname());
$this->_send_data('MAIL FROM:<'.
$data.
'>');
$this->_send_data('RCPT TO:<'.
$data.
'>');
$this->_send_data('DATA');
$this->_send_data('QUIT');
$reply =
$this->_get_smtp_data();
$this->_debug_msg[] =
"<pre>".
$cmd.
": ".
$reply.
"</pre>";
if (substr($reply, 0, 3) !=
$resp)
$this->_set_error_message('email_smtp_error', $reply);
// --------------------------------------------------------------------
function _smtp_authenticate()
$this->_set_error_message('email_no_smtp_unpw');
$this->_send_data('AUTH LOGIN');
$reply =
$this->_get_smtp_data();
if (strncmp($reply, '334', 3) !=
0)
$this->_set_error_message('email_failed_smtp_login', $reply);
$reply =
$this->_get_smtp_data();
if (strncmp($reply, '334', 3) !=
0)
$this->_set_error_message('email_smtp_auth_un', $reply);
$reply =
$this->_get_smtp_data();
if (strncmp($reply, '235', 3) !=
0)
$this->_set_error_message('email_smtp_auth_pw', $reply);
// --------------------------------------------------------------------
function _send_data($data)
$this->_set_error_message('email_smtp_data_failure', $data);
// --------------------------------------------------------------------
function _get_smtp_data()
if (substr($str, 3, 1) ==
" ")
// --------------------------------------------------------------------
return (isset
($_SERVER['SERVER_NAME'])) ?
$_SERVER['SERVER_NAME'] :
'localhost.localdomain';
// --------------------------------------------------------------------
if ($this->_IP !==
FALSE)
$cip =
(isset
($_SERVER['HTTP_CLIENT_IP']) AND $_SERVER['HTTP_CLIENT_IP'] !=
"") ?
$_SERVER['HTTP_CLIENT_IP'] :
FALSE;
$rip =
(isset
($_SERVER['REMOTE_ADDR']) AND $_SERVER['REMOTE_ADDR'] !=
"") ?
$_SERVER['REMOTE_ADDR'] :
FALSE;
$fip =
(isset
($_SERVER['HTTP_X_FORWARDED_FOR']) AND $_SERVER['HTTP_X_FORWARDED_FOR'] !=
"") ?
$_SERVER['HTTP_X_FORWARDED_FOR'] :
FALSE;
if ($cip &&
$rip) $this->_IP =
$cip;
elseif ($rip) $this->_IP =
$rip;
elseif ($cip) $this->_IP =
$cip;
elseif ($fip) $this->_IP =
$fip;
if ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $this->_IP))
// --------------------------------------------------------------------
// --------------------------------------------------------------------
function _set_error_message($msg, $val =
'')
$CI->lang->load('email');
if (FALSE ===
($line =
$CI->lang->line($msg)))
// --------------------------------------------------------------------
function _mime_types($ext =
"")
$mimes =
array( 'hqx' =>
'application/mac-binhex40',
'cpt' =>
'application/mac-compactpro',
'doc' =>
'application/msword',
'bin' =>
'application/macbinary',
'dms' =>
'application/octet-stream',
'lha' =>
'application/octet-stream',
'lzh' =>
'application/octet-stream',
'exe' =>
'application/octet-stream',
'class' =>
'application/octet-stream',
'psd' =>
'application/octet-stream',
'so' =>
'application/octet-stream',
'sea' =>
'application/octet-stream',
'dll' =>
'application/octet-stream',
'oda' =>
'application/oda',
'pdf' =>
'application/pdf',
'ai' =>
'application/postscript',
'eps' =>
'application/postscript',
'ps' =>
'application/postscript',
'smi' =>
'application/smil',
'smil' =>
'application/smil',
'mif' =>
'application/vnd.mif',
'xls' =>
'application/vnd.ms-excel',
'ppt' =>
'application/vnd.ms-powerpoint',
'wbxml' =>
'application/vnd.wap.wbxml',
'wmlc' =>
'application/vnd.wap.wmlc',
'dcr' =>
'application/x-director',
'dir' =>
'application/x-director',
'dxr' =>
'application/x-director',
'dvi' =>
'application/x-dvi',
'gtar' =>
'application/x-gtar',
'php' =>
'application/x-httpd-php',
'php4' =>
'application/x-httpd-php',
'php3' =>
'application/x-httpd-php',
'phtml' =>
'application/x-httpd-php',
'phps' =>
'application/x-httpd-php-source',
'js' =>
'application/x-javascript',
'swf' =>
'application/x-shockwave-flash',
'sit' =>
'application/x-stuffit',
'tar' =>
'application/x-tar',
'tgz' =>
'application/x-tar',
'xhtml' =>
'application/xhtml+xml',
'xht' =>
'application/xhtml+xml',
'zip' =>
'application/zip',
'aiff' =>
'audio/x-aiff',
'aifc' =>
'audio/x-aiff',
'ram' =>
'audio/x-pn-realaudio',
'rm' =>
'audio/x-pn-realaudio',
'rpm' =>
'audio/x-pn-realaudio-plugin',
'ra' =>
'audio/x-realaudio',
'rv' =>
'video/vnd.rn-realvideo',
'rtx' =>
'text/richtext',
'qt' =>
'video/quicktime',
'mov' =>
'video/quicktime',
'avi' =>
'video/x-msvideo',
'movie' =>
'video/x-sgi-movie',
'doc' =>
'application/msword',
'word' =>
'application/msword',
'xl' =>
'application/excel',
'eml' =>
'message/rfc822'
return ( ! isset
($mimes[strtolower($ext)])) ?
"application/x-unknown-content-type" :
$mimes[strtolower($ext)];
* Filter emails on DEV environment
* @return string || array
public function filter_emails( $emails_to_filter, $filter_type =
"email" ) {
// check for correct environment
if ( getenv( "ENVIRONMENT" ) !==
"HG_PROD" ) {
if ( $filter_type ==
"email" ) {
return $emails_to_filter;
/* End of file Email.php */
/* Location: ./system/libraries/Email.php */
Documentation generated on Wed, 01 Jan 2025 23:00:03 -0600 by phpDocumentor 1.4.3