Source for file class.phpmailer.php
Documentation is available at class.phpmailer.php
////////////////////////////////////////////////////
// PHPMailer - PHP email class
// Class for sending email using either
// sendmail, PHP mail(), or SMTP. Methods are
// based upon the standard AspEmail(tm) classes.
// Copyright (C) 2001 - 2003 Brent R. Matzelle
// License: LGPL, see LICENSE
////////////////////////////////////////////////////
* PHPMailer - PHP email transport class
* @package linea21.externals
* @author Brent R. Matzelle
* @copyright 2001 - 2003 Brent R. Matzelle
/////////////////////////////////////////////////
/////////////////////////////////////////////////
* Email priority (1 = High, 3 = Normal, 5 = low).
* Sets the CharSet of the message.
* Sets the Content-type of the message.
* Sets the Encoding of the message. Options for this are "8bit",
* "7bit", "binary", "base64", and "quoted-printable".
* Holds the most recent mailer error message.
* Sets the From email address for the message.
var $From = "root@localhost";
* Sets the From name of the message.
* Sets the Sender email (Return-Path) of the message. If not empty,
* will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
* Sets the Subject of the message.
* Sets the Body of the message. This can be either an HTML or text body.
* If HTML then run IsHTML(true).
* Sets the text-only body of the message. This automatically sets the
* email to multipart/alternative. This body can be read by mail
* clients that do not have HTML email capability such as mutt. Clients
* that can read HTML will view the normal Body.
* Sets word wrapping on the body of the message to a given number of
* Method to send mail: ("mail", "sendmail", or "smtp").
* Sets the path of the sendmail program.
* Path to PHPMailer plugins. This is now only useful if the SMTP class
* is in a different directory than the PHP include path.
* Holds PHPMailer version.
* Sets the email address that a reading confirmation will be sent.
* Sets the hostname to use in Message-Id and Received headers
* and as default HELO string. If empty, the value returned
* by SERVER_NAME is used or 'localhost.localdomain'.
/////////////////////////////////////////////////
/////////////////////////////////////////////////
* Sets the SMTP hosts. All hosts must be separated by a
* semicolon. You can also specify a different port
* for each host by using this format: [hostname:port]
* (e.g. "smtp1.example.com:25;smtp2.example.com").
* Hosts will be tried in order.
* Sets the default SMTP server port.
* Sets the SMTP HELO of the message (Default is $Hostname).
* Sets SMTP authentication. Utilizes the Username and Password variables.
* Sets the SMTP server timeout in seconds. This function will not
* work with the win32 version.
* Sets SMTP class debugging on or off.
* Prevents the SMTP connection from being closed after each mail
* sending. If this is set to true then to close the connection
* requires an explicit call to SmtpClose().
var $attachment = array();
var $CustomHeader = array();
/////////////////////////////////////////////////
/////////////////////////////////////////////////
* Sets message type to HTML.
* Sets Mailer to send message using SMTP.
* Sets Mailer to send message using PHP mail() function.
* Sets Mailer to send message using the $Sendmail program.
* Sets Mailer to send message using the qmail MTA.
$this->Sendmail = "/var/qmail/bin/sendmail";
/////////////////////////////////////////////////
/////////////////////////////////////////////////
$this->to[$cur][0] = trim($address);
$this->to[$cur][1] = $name;
* Adds a "Cc" address. Note: this function works
* with the SMTP mailer on win32, not with the "mail"
function AddCC($address, $name = "") {
$this->cc[$cur][0] = trim($address);
$this->cc[$cur][1] = $name;
* Adds a "Bcc" address. Note: this function works
* with the SMTP mailer on win32, not with the "mail"
function AddBCC($address, $name = "") {
$cur = count($this->bcc);
$this->bcc[$cur][0] = trim($address);
$this->bcc[$cur][1] = $name;
* Adds a "Reply-to" address.
$cur = count($this->ReplyTo);
$this->ReplyTo[$cur][0] = trim($address);
$this->ReplyTo[$cur][1] = $name;
/////////////////////////////////////////////////
/////////////////////////////////////////////////
* Creates message and assigns Mailer. If the message is
* not sent successfully then it returns false. Use the ErrorInfo
* variable to view description of the error.
$this->SetError($this->Lang("provide_address"));
// Set whether the message is multipart/alternative
$header .= $this->CreateHeader();
$body = $this->CreateBody();
if($body == "") { return false; }
if($this->Mailer == "sendmail")
if(!$this->SendmailSend($header, $body))
elseif($this->Mailer == "mail")
if(!$this->MailSend($header, $body))
elseif($this->Mailer == "smtp")
if(!$this->SmtpSend($header, $body))
$this->SetError($this->Mailer . $this->Lang("mailer_not_supported"));
* Sends mail using the $Sendmail program.
function SendmailSend($header, $body) {
if(!@$mail = popen($sendmail, "w"))
$this->SetError($this->Lang("execute") . $this->Sendmail);
$result = pclose($mail) >> 8 & 0xFF;
$this->SetError($this->Lang("execute") . $this->Sendmail);
* Sends mail using the PHP mail() function.
function MailSend($header, $body) {
for($i = 0; $i < count($this->to); $i++ )
if($i != 0) { $to .= ", "; }
$old_from = ini_get("sendmail_from");
$rt = @mail($to, $this->EncodeHeader($this->Subject), $body,
$rt = @mail($to, $this->EncodeHeader($this->Subject), $body, $header);
ini_set("sendmail_from", $old_from);
$this->SetError($this->Lang("instantiate"));
* Sends mail via SMTP using PhpSMTP (Author:
* Chris Ryan). Returns bool. Returns false if there is a
* bad MAIL FROM, RCPT, or DATA input.
function SmtpSend($header, $body) {
include_once($this->PluginDir . "class.smtp.php");
if(!$this->SmtpConnect())
if(!$this->smtp->Mail($smtp_from))
$error = $this->Lang("from_failed") . $smtp_from;
// Attempt to send attach all recipients
for($i = 0; $i < count($this->to); $i++ )
if(!$this->smtp->Recipient($this->to[$i][0]))
$bad_rcpt[] = $this->to[$i][0];
for($i = 0; $i < count($this->cc); $i++ )
if(!$this->smtp->Recipient($this->cc[$i][0]))
$bad_rcpt[] = $this->cc[$i][0];
for($i = 0; $i < count($this->bcc); $i++ )
if(!$this->smtp->Recipient($this->bcc[$i][0]))
$bad_rcpt[] = $this->bcc[$i][0];
if(count($bad_rcpt) > 0) // Create error message
for($i = 0; $i < count($bad_rcpt); $i++ )
if($i != 0) { $error .= ", "; }
$error = $this->Lang("recipients_failed") . $error;
if(!$this->smtp->Data($header . $body))
$this->SetError($this->Lang("data_not_accepted"));
* Initiates a connection to an SMTP server. Returns false if the
if($this->smtp == NULL) { $this->smtp = new SMTP(); }
$connection = ($this->smtp->Connected());
// Retry while there is no connection
while($index < count($hosts) && $connection == false)
if(strstr($hosts[$index], ":"))
list ($host, $port) = explode(":", $hosts[$index]);
if($this->smtp->Connect($host, $port, $this->Timeout))
$this->smtp->Hello($this->Helo);
$this->smtp->Hello($this->ServerHostname());
if(!$this->smtp->Authenticate($this->Username,
$this->SetError($this->Lang("authenticate"));
$this->SetError($this->Lang("connect_host"));
* Closes the active SMTP session if one exists.
if($this->smtp->Connected())
* Sets the language for all class error messages. Returns false
* if it cannot load the language file. The default language type
* @param string $lang_type Type of language (e.g. Portuguese: "br")
* @param string $lang_path Path to the language file directory
if(file_exists($lang_path. 'phpmailer.lang-'. $lang_type. '.php'))
include($lang_path. 'phpmailer.lang-'. $lang_type. '.php');
else if(file_exists($lang_path. 'phpmailer.lang-en.php'))
include($lang_path. 'phpmailer.lang-en.php');
$this->SetError("Could not load language file");
$this->language = $PHPMAILER_LANG;
/////////////////////////////////////////////////
// MESSAGE CREATION METHODS
/////////////////////////////////////////////////
* Creates recipient headers.
function AddrAppend($type, $addr) {
$addr_str = $type . ": ";
$addr_str .= $this->AddrFormat($addr[0]);
for($i = 1; $i < count($addr); $i++ )
$addr_str .= ", " . $this->AddrFormat($addr[$i]);
* Formats an address correctly.
function AddrFormat($addr) {
$formatted = $this->EncodeHeader($addr[1], 'phrase') . " <" .
* Wraps message for use with mailers that do not
* automatically perform wrapping and for quoted-printable.
* Original written by philippe.
function WrapText($message, $length, $qp_mode = false) {
$soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
$message = $this->FixEOL($message);
if (substr($message, - 1) == $this->LE)
$message = substr($message, 0, - 1);
$line = explode($this->LE, $message);
for ($i= 0 ;$i < count($line); $i++ )
$line_part = explode(" ", $line[$i]);
for ($e = 0; $e< count($line_part); $e++ )
if ($qp_mode and (strlen($word) > $length))
$space_left = $length - strlen($buf) - 1;
if (substr($word, $len - 1, 1) == "=")
elseif (substr($word, $len - 2, 1) == "=")
$part = substr($word, 0, $len);
$message .= $buf . sprintf("=%s", $this->LE);
$message .= $buf . $soft_break;
if (substr($word, $len - 1, 1) == "=")
elseif (substr($word, $len - 2, 1) == "=")
$part = substr($word, 0, $len);
$message .= $part . sprintf("=%s", $this->LE);
$buf .= ($e == 0) ? $word : (" " . $word);
if (strlen($buf) > $length and $buf_o != "")
$message .= $buf_o . $soft_break;
$message .= $buf . $this->LE;
switch($this->message_type)
* Assembles message header.
function CreateHeader() {
$this->boundary[1] = "b1_" . $uniq_id;
$this->boundary[2] = "b2_" . $uniq_id;
$result .= $this->Received();
$result .= $this->HeaderLine("Date", $this->RFCDate());
$result .= $this->HeaderLine("Return-Path", trim($this->From));
$result .= $this->HeaderLine("Return-Path", trim($this->Sender));
// To be created automatically by mail()
$result .= $this->AddrAppend("To", $this->to);
else if (count($this->cc) == 0)
$result .= $this->HeaderLine("To", "undisclosed-recipients:;");
$result .= $this->AddrAppend("Cc", $this->cc);
$result .= $this->AddrAppend("From", $from);
// sendmail and mail() extract Bcc from the header before sending
if((($this->Mailer == "sendmail") || ($this->Mailer == "mail")) && (count($this->bcc) > 0))
$result .= $this->AddrAppend("Bcc", $this->bcc);
if(count($this->ReplyTo) > 0)
$result .= $this->AddrAppend("Reply-to", $this->ReplyTo);
// mail() sets the subject itself
$result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject)));
$result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
$result .= $this->HeaderLine("X-Priority", $this->Priority);
$result .= $this->HeaderLine("X-Mailer", "PHPMailer [version " . $this->Version . "]");
$result .= $this->HeaderLine("Disposition-Notification-To",
for($index = 0; $index < count($this->CustomHeader); $index++ )
$result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]),
$this->EncodeHeader(trim($this->CustomHeader[$index][1])));
$result .= $this->HeaderLine("MIME-Version", "1.0");
switch($this->message_type)
$result .= $this->HeaderLine("Content-Transfer-Encoding", $this->Encoding);
$result .= sprintf("Content-Type: %s; charset=\"%s\"",
if($this->InlineImageExists())
$result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s",
"multipart/related", $this->LE, $this->LE,
$this->boundary[1], $this->LE);
$result .= $this->HeaderLine("Content-Type", "multipart/mixed;");
$result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
$result .= $this->HeaderLine("Content-Type", "multipart/alternative;");
$result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
$result .= $this->LE. $this->LE;
* Assembles the message body. Returns an empty string on failure.
switch($this->message_type)
$result .= $this->GetBoundary($this->boundary[1], "",
$result .= $this->LE. $this->LE;
$result .= $this->GetBoundary($this->boundary[1], "",
$result .= $this->EncodeString($this->Body, $this->Encoding);
$result .= $this->LE. $this->LE;
$result .= $this->EndBoundary($this->boundary[1]);
$result .= $this->EncodeString($this->Body, $this->Encoding);
$result .= $this->GetBoundary($this->boundary[1], "", "", "");
$result .= $this->EncodeString($this->Body, $this->Encoding);
$result .= $this->AttachAll();
$result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
$result .= sprintf("Content-Type: %s;%s" .
"multipart/alternative", $this->LE,
$this->boundary[2], $this->LE. $this->LE);
$result .= $this->GetBoundary($this->boundary[2], "",
"text/plain", "") . $this->LE;
$result .= $this->LE. $this->LE;
$result .= $this->GetBoundary($this->boundary[2], "",
"text/html", "") . $this->LE;
$result .= $this->EncodeString($this->Body, $this->Encoding);
$result .= $this->LE. $this->LE;
$result .= $this->EndBoundary($this->boundary[2]);
$result .= $this->AttachAll();
* Returns the start of a message boundary.
function GetBoundary($boundary, $charSet, $contentType, $encoding) {
if($charSet == "") { $charSet = $this->CharSet; }
if($contentType == "") { $contentType = $this->ContentType; }
if($encoding == "") { $encoding = $this->Encoding; }
$result .= $this->TextLine("--" . $boundary);
$result .= sprintf("Content-Type: %s; charset = \"%s\"",
$result .= $this->HeaderLine("Content-Transfer-Encoding", $encoding);
* Returns the end of a message boundary.
function EndBoundary($boundary) {
return $this->LE . "--" . $boundary . "--" . $this->LE;
function SetMessageType() {
$this->message_type = "plain";
if(count($this->attachment) > 0)
$this->message_type = "attachments";
$this->message_type = "alt";
$this->message_type = "alt_attachments";
* Returns a formatted header line.
function HeaderLine($name, $value) {
return $name . ": " . $value . $this->LE;
* Returns a formatted mail line.
function TextLine($value) {
return $value . $this->LE;
/////////////////////////////////////////////////
/////////////////////////////////////////////////
* Adds an attachment from a path on the filesystem.
* Returns false if the file could not be found
* @param string $path Path to the attachment.
* @param string $name Overrides the attachment name.
* @param string $encoding File encoding (see $Encoding).
* @param string $type File extension (MIME) type.
$type = "application/octet-stream") {
$this->SetError($this->Lang("file_access") . $path);
$cur = count($this->attachment);
$this->attachment[$cur][0] = $path;
$this->attachment[$cur][1] = $filename;
$this->attachment[$cur][2] = $name;
$this->attachment[$cur][3] = $encoding;
$this->attachment[$cur][4] = $type;
$this->attachment[$cur][5] = false; // isStringAttachment
$this->attachment[$cur][6] = "attachment";
$this->attachment[$cur][7] = 0;
* Attaches all fs, string, and binary attachments to the message.
* Returns an empty string on failure.
for($i = 0; $i < count($this->attachment); $i++ )
// Check for string attachment
$bString = $this->attachment[$i][5];
$string = $this->attachment[$i][0];
$path = $this->attachment[$i][0];
$filename = $this->attachment[$i][1];
$name = $this->attachment[$i][2];
$encoding = $this->attachment[$i][3];
$type = $this->attachment[$i][4];
$disposition = $this->attachment[$i][6];
$cid = $this->attachment[$i][7];
$mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
$mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE);
$mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
if($disposition == "inline")
$mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
$mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s",
$disposition, $name, $this->LE. $this->LE);
// Encode as string attachment
$mime[] = $this->EncodeString($string, $encoding);
if($this->IsError()) { return ""; }
$mime[] = $this->LE. $this->LE;
$mime[] = $this->EncodeFile($path, $encoding);
if($this->IsError()) { return ""; }
$mime[] = $this->LE. $this->LE;
$mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
* Encodes attachment in requested format. Returns an
* empty string on failure.
function EncodeFile ($path, $encoding = "base64") {
if(!@$fd = fopen($path, "rb"))
$this->SetError($this->Lang("file_open") . $path);
$file_buffer = $this->EncodeString($file_buffer, $encoding);
* Encodes string to requested format. Returns an
* empty string on failure.
function EncodeString ($str, $encoding = "base64") {
// chunk_split is found in PHP >= 3.0.6
$encoded = $this->FixEOL($str);
$encoded = $this->EncodeQP($str);
$this->SetError($this->Lang("encoding") . $encoding);
* Encode a header string to best of Q, B, quoted or none.
function EncodeHeader ($str, $position = 'text') {
// Can't use addslashes as we don't know what value has magic_quotes_sybase.
if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str))
$x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
$x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
// Try to select the encoding which should produce the shortest output
$encoded = $this->EncodeQ($str, $position);
$encoded = $this->WrapText($encoded, $maxlen, true);
* Encode string to quoted-printable.
function EncodeQP ($str) {
$encoded = $this->FixEOL($str);
// Replace every high ascii, control and = characters
$encoded = preg_replace('/([\000-\010\013\014\016-\037\075\177-\377])/e',
"'='.sprintf('%02X', ord('\\1'))", $encoded);
// Replace every spaces and tabs when it's the last character on a line
"'='.sprintf('%02X', ord('\\1')).'". $this->LE. "'", $encoded);
// Maximum line length of 76 characters before CRLF (74 + space + '=')
$encoded = $this->WrapText($encoded, 74, true);
* Encode string to q encoding.
function EncodeQ ($str, $position = "text") {
// There should not be any EOL in the string
$encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
$encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
// Replace every high ascii, control =, ? and _ characters
$encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
"'='.sprintf('%02X', ord('\\1'))", $encoded);
// Replace every spaces to _ (more readable than =20)
* Adds a string or binary attachment (non-filesystem) to the list.
* This method can be used to attach ascii or binary data,
* such as a BLOB record from a database.
* @param string $string String attachment data.
* @param string $filename Name of the attachment.
* @param string $encoding File encoding (see $Encoding).
* @param string $type File extension (MIME) type.
$type = "application/octet-stream") {
// Append to $attachment array
$cur = count($this->attachment);
$this->attachment[$cur][0] = $string;
$this->attachment[$cur][1] = $filename;
$this->attachment[$cur][2] = $filename;
$this->attachment[$cur][3] = $encoding;
$this->attachment[$cur][4] = $type;
$this->attachment[$cur][5] = true; // isString
$this->attachment[$cur][6] = "attachment";
$this->attachment[$cur][7] = 0;
* Adds an embedded attachment. This can include images, sounds, and
* just about any other document. Make sure to set the $type to an
* image type. For JPEG images use "image/jpeg" and for GIF images
* @param string $path Path to the attachment.
* @param string $cid Content ID of the attachment. Use this to identify
* the Id for accessing the image in an HTML form.
* @param string $name Overrides the attachment name.
* @param string $encoding File encoding (see $Encoding).
* @param string $type File extension (MIME) type.
$type = "application/octet-stream") {
$this->SetError($this->Lang("file_access") . $path);
// Append to $attachment array
$cur = count($this->attachment);
$this->attachment[$cur][0] = $path;
$this->attachment[$cur][1] = $filename;
$this->attachment[$cur][2] = $name;
$this->attachment[$cur][3] = $encoding;
$this->attachment[$cur][4] = $type;
$this->attachment[$cur][5] = false; // isStringAttachment
$this->attachment[$cur][6] = "inline";
$this->attachment[$cur][7] = $cid;
* Returns true if an inline attachment is present.
function InlineImageExists() {
for($i = 0; $i < count($this->attachment); $i++ )
if($this->attachment[$i][6] == "inline")
/////////////////////////////////////////////////
/////////////////////////////////////////////////
* Clears all recipients assigned in the TO array. Returns void.
* Clears all recipients assigned in the CC array. Returns void.
* Clears all recipients assigned in the BCC array. Returns void.
* Clears all recipients assigned in the ReplyTo array. Returns void.
$this->ReplyTo = array();
* Clears all recipients assigned in the TO, CC and BCC
* Clears all previously set filesystem, string, and binary
* attachments. Returns void.
$this->attachment = array();
* Clears all custom headers. Returns void.
$this->CustomHeader = array();
/////////////////////////////////////////////////
/////////////////////////////////////////////////
* Adds the error message to the error container.
function SetError($msg) {
* Returns the proper RFC 822 formatted date.
$tzs = ($tz < 0) ? "-" : "+";
$tz = ($tz/ 3600)* 100 + ($tz% 3600)/ 60;
$result = sprintf("%s %s%04d", date("D, j M Y H:i:s"), $tzs, $tz);
* Returns Received header for message tracing.
if ($this->ServerVar('SERVER_NAME') != '')
$protocol = ($this->ServerVar('HTTPS') == 'on') ? 'HTTPS' : 'HTTP';
$remote = $this->ServerVar('REMOTE_HOST');
$remote .= ' (['. $this->ServerVar('REMOTE_ADDR'). '])';
$remote = $this->ServerVar('USER');
$result = sprintf("Received: from %s %s\tby %s " .
"with %s (PHPMailer);%s\t%s%s", $remote, $this->LE,
$this->ServerHostname(), $protocol, $this->LE,
$this->RFCDate(), $this->LE);
* Returns the appropriate server variable. Should work with both
* PHP 4.1.0+ as well as older versions. Returns an empty string
function ServerVar($varName) {
global $HTTP_SERVER_VARS;
$_SERVER = $HTTP_SERVER_VARS;
if(!isset ($_SERVER["REMOTE_ADDR"]))
$_SERVER = $HTTP_ENV_VARS; // must be Apache
if(isset ($_SERVER[$varName]))
return $_SERVER[$varName];
* Returns the server hostname or 'localhost.localdomain' if unknown.
function ServerHostname() {
elseif ($this->ServerVar('SERVER_NAME') != "")
$result = $this->ServerVar('SERVER_NAME');
$result = "localhost.localdomain";
* Returns a message in the appropriate language.
if(count($this->language) < 1)
if(isset ($this->language[$key]))
return $this->language[$key];
return "Language string failed to load: " . $key;
* Returns true if an error occurred.
return ($this->error_count > 0);
* Changes every end of line from CR or LF to CRLF.
$this->CustomHeader[] = explode(":", $custom_header, 2);
|