topical media & game development
professional-ajax-09-AjaxMail-inc-phpmailer-class.phpmailer.php / php
<?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 PHPMailer
author: Brent R. Matzelle
@copyright 2001 - 2003 Brent R. Matzelle
class PHPMailer
{
//////////////////////////////////////////////
// PUBLIC VARIABLES
//////////////////////////////////////////////
Email priority (1 = High, 3 = Normal, 5 = low).
@var int
var
Sets the CharSet of the message.
@var string
var CharSet = "iso-8859-1";
Sets the Content-type of the message.
@var string
var
Sets the Encoding of the message. Options for this are "8bit",
"7bit", "binary", "base64", and "quoted-printable".
@var string
var Encoding = "8bit";
Holds the most recent mailer error message.
@var string
var
Sets the From email address for the message.
@var string
var From = "root@localhost";
Sets the From name of the message.
@var string
var
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.
@var string
var Sender = "";
Sets the Subject of the message.
@var string
var
Sets the Body of the message. This can be either an HTML or text body.
If HTML then run IsHTML(true).
@var string
var Body = "";
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.
@var string
var
Sets word wrapping on the body of the message to a given number of
characters.
@var int
var WordWrap = 0;
Method to send mail: ("mail", "sendmail", or "smtp").
@var string
var
Sets the path of the sendmail program.
@var string
var Sendmail = "/usr/sbin/sendmail";
Path to PHPMailer plugins. This is now only useful if the SMTP class
is in a different directory than the PHP include path.
@var string
var
Holds PHPMailer version.
@var string
var Version = "1.73";
Sets the email address that a reading confirmation will be sent.
@var string
var
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'.
@var string
var Hostname = "";
//////////////////////////////////////////////
// SMTP VARIABLES
//////////////////////////////////////////////
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.
@var string
var
Sets the default SMTP server port.
@var int
var Port = 25;
Sets the SMTP HELO of the message (Default is
var Helo = "";
Sets SMTP authentication. Utilizes the Username and Password variables.
@var bool
var
Sets SMTP username.
@var string
var Username = "";
Sets SMTP password.
@var string
var
Sets the SMTP server timeout in seconds. This function will not
work with the win32 version.
@var int
var Timeout = 10;
Sets SMTP class debugging on or off.
@var bool
var
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 bool
var SMTPKeepAlive = false;
#@+
@access private
var to = array();
var bcc = array();
var attachment = array();
var message_type = "";
var language = array();
var LE = "\n";
#@-
//////////////////////////////////////////////
// VARIABLE METHODS
//////////////////////////////////////////////
Sets message type to HTML.
parameter: bool
function IsHTML(bool) {
if(this->ContentType = "text/html";
else
Sets Mailer to send message using SMTP.
returns: void
function IsSMTP() {
this->Mailer = "smtp";
}
Sets Mailer to send message using PHP mail() function.
returns: void
function IsMail() {
Sets Mailer to send message using the Sendmail program.
returns: void
function IsSendmail() {
Sets Mailer to send message using the qmail MTA.
returns: void
function IsQmail() {
this->Sendmail = "/var/qmail/bin/sendmail";
//////////////////////////////////////////////
// RECIPIENT METHODS
//////////////////////////////////////////////
Adds a "To" address.
parameter: string address
parameter: string
function AddAddress(address, cur = count(this->to[address);
cur][1] =
Adds a "Cc" address. Note: this function works
with the SMTP mailer on win32, not with the "mail"
mailer.
parameter: string address
parameter: string
function AddCC(address, cur = count(this->cc[address);
cur][1] =
Adds a "Bcc" address. Note: this function works
with the SMTP mailer on win32, not with the "mail"
mailer.
parameter: string address
parameter: string
function AddBCC(address, cur = count(this->bcc[address);
cur][1] =
Adds a "Reply-to" address.
parameter: string address
parameter: string
function AddReplyTo(address, cur = count(this->ReplyTo[address);
cur][1] = //////////////////////////////////////////////
// MAIL SENDING METHODS
//////////////////////////////////////////////
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.
returns: bool
function Send() {
header = "";
result = true;
if((count(this->cc) + count(this->SetError(this->AltBody))
this->error_count = 0; // reset errors
header .= body = body == "") { return false; }
// Choose the mailer
switch(result = header, result = header, result = header, this->SetError(this->Lang("mailer_not_supported"));
result;
}
Sends mail using the
function SendmailSend(header, this->Sender != "")
this->Sendmail, sendmail = sprintf("\%s -oi -t", mail = popen(this->SetError(this->Sendmail);
return false;
}
fputs(header);
fputs(body);
mail) >> 8 & 0xFF;
if(this->SetError(this->Sendmail);
return false;
}
return true;
}
Sends mail using the PHP mail() function.
@access private
returns: bool
function MailSend(body) {
i = 0; this->to); i != 0) { to .= i][0];
}
if (old_from = ini_get("sendmail_from");
ini_set("sendmail_from", params = sprintf("-oi -f \%s", rt = @mail(this->EncodeHeader(body,
params);
}
else
to, this->Subject), header);
if (isset(old_from);
if(!this->SetError(
Sends mail via SMTP using PhpSMTP (Author:
Chris Ryan). Returns bool. Returns false if there is a
bad MAIL FROM, RCPT, or DATA input.
@access private
returns: bool
function SmtpSend(header, this->PluginDir . "class.smtp.php");
bad_rcpt = array();
if(!smtp_from = (this->From : this->smtp->Mail(error = smtp_from;
error);
i = 0; this->to); this->smtp->Recipient(i][0]))
this->to[i = 0; this->cc); this->smtp->Recipient(i][0]))
this->cc[i = 0; this->bcc); this->smtp->Recipient(i][0]))
this->bcc[bad_rcpt) > 0) // Create error message
{
for(i < count(i++)
{
if(error .= ", "; }
bad_rcpt[error = error;
error);
this->smtp->Data(body))
{
this->Lang("data_not_accepted"));
this->SMTPKeepAlive == true)
this->SmtpClose();
return true;
}
Initiates a connection to an SMTP server. Returns false if the
operation failed.
@access private
returns: bool
function SmtpConnect() {
if(this->smtp = new SMTP(); }
this->SMTPDebug;
this->Host);
connection = (index < count(connection == false)
{
if(strstr(index], ":"))
list(port) = explode(":", index]);
else
{
hosts[port = this->smtp->Connect(port, this->Helo != '')
this->Helo);
else
this->ServerHostname());
if(this->smtp->Authenticate(this->Password))
{
this->Lang("authenticate"));
connection = false;
}
}
index++;
}
if(!this->SetError(connection;
}
Closes the active SMTP session if one exists.
returns: void
function SmtpClose() {
if(this->smtp->Connected())
{
this->smtp->Close();
}
}
}
Sets the language for all class error messages. Returns false
if it cannot load the language file. The default language type
is English.
parameter: string lang_path Path to the language file directory
@access public
returns: bool
function SetLanguage(lang_path = "language/") {
if(file_exists(lang_type.'.php'))
include(lang_type.'.php');
else if(file_exists(lang_path.'phpmailer.lang-en.php');
else
{
this->language = //////////////////////////////////////////////
// MESSAGE CREATION METHODS
//////////////////////////////////////////////
Creates recipient headers.
@access private
returns: string
function AddrAppend(type, addr_str = addr_str .= addr[0]);
if(count(i = 1; addr); addr_str .= ", " . addr[addr_str .= addr_str;
}
Formats an address correctly.
@access private
returns: string
function AddrFormat(addr[1]))
addr[0];
else
{
this->EncodeHeader(addr[0] . ">";
}
return
Wraps message for use with mailers that do not
automatically perform wrapping and for quoted-printable.
Original written by philippe.
@access private
returns: string
function WrapText(message, qp_mode = false) {
qp_mode) ? sprintf(" =\%s", this->LE;
this->FixEOL(message, -1) == message = substr(line = explode(message);
i=0 ;line); line_part = explode(" ", i]);
e = 0; line_part); word = e];
if (word) > space_left = buf) - 1;
if (space_left > 20)
{
space_left;
if (substr(len - 1, 1) == "=")
word, len -= 2;
word, 0, word = substr(len);
part;
buf . sprintf("=\%s", message .= soft_break;
}
word) > 0)
{
length;
if (substr(len - 1, 1) == "=")
word, len -= 2;
word, 0, word = substr(len);
if (strlen(message .= this->LE);
else
part;
}
}
else
{
buf;
e == 0) ? word);
if (strlen(length and message .= soft_break;
word;
}
}
}
buf . message;
}
Set the body wrapping.
@access private
returns: void
function SetWordWrap() {
if(this->message_type)
{
case "alt":
// fall through
case "alt_attachments":
this->WrapText(this->WordWrap);
break;
default:
this->WrapText(this->WordWrap);
break;
}
}
Assembles message header.
@access private
returns: string
function CreateHeader() {
uniq_id = md5(uniqid(time()));
uniq_id;
uniq_id;
this->HeaderLine("Date", this->Sender == "")
this->HeaderLine("Return-Path", trim(result .= this->Sender));
// To be created automatically by mail()
if(this->to) > 0)
this->AddrAppend("To", this->cc) == 0)
this->HeaderLine("To", "undisclosed-recipients:;");
if(count(result .= this->cc);
}
from[0][0] = trim(from[0][1] = result .= from);
// sendmail and mail() extract Bcc from the header before sending
if(((this->Mailer == "mail")) && (count(result .= this->bcc);
if(count(result .= this->ReplyTo);
// mail() sets the subject itself
if(result .= this->EncodeHeader(trim(result .= sprintf("Message-ID: <\%s@\%s>\%s", this->ServerHostname(), result .= this->Priority);
this->HeaderLine("X-Mailer", "PHPMailer [version " . this->ConfirmReadingTo != "")
{
this->HeaderLine("Disposition-Notification-To",
"<" . trim(index = 0; this->CustomHeader); result .= this->CustomHeader[this->EncodeHeader(trim(index][1])));
}
this->HeaderLine("MIME-Version", "1.0");
switch(result .= this->Encoding);
this->ContentType, this->InlineImageExists())
{
this->LE, this->boundary[1], result .= result .= this->boundary[1] . '"');
}
break;
case "alt":
this->HeaderLine("Content-Type", "multipart/alternative;");
this->TextLine("\tboundary=\"" . this->Mailer != "mail")
this->LE.result;
}
Assembles the message body. Returns an empty string on failure.
@access private
returns: string
function CreateBody() {
this->SetWordWrap();
switch(result .= this->boundary[1], "",
"text/plain", "");
this->EncodeString(this->Encoding);
this->LE.result .= this->boundary[1], "",
"text/html", "");
this->EncodeString(this->Encoding);
this->LE.result .= this->boundary[1]);
break;
case "plain":
this->EncodeString(this->Encoding);
break;
case "attachments":
this->GetBoundary(result .= this->Body, result .= result .= result .= sprintf("--\%s\%s", this->LE);
this->LE,
this->LE.result .= this->boundary[2], "",
"text/plain", "") . result .= this->AltBody, result .= this->LE;
// Create the HTML body
this->GetBoundary(this->LE;
this->EncodeString(this->Encoding);
this->LE.result .= this->boundary[2]);
this->AttachAll();
break;
}
if(result = "";
return
Returns the start of a message boundary.
@access private
function GetBoundary(boundary, contentType, result = "";
if(charSet = contentType == "") { this->ContentType; }
if(encoding = result .= boundary);
contentType, result .= result .= encoding);
this->LE;
return
Returns the end of a message boundary.
@access private
function EndBoundary(boundary) {
return boundary . "--" .
Sets the message type.
@access private
returns: void
function SetMessageType() {
if(count(this->attachment) < 1 && strlen(this->message_type = "plain";
else
{
if(count(this->message_type = "attachments";
if(strlen(this->attachment) < 1)
this->AltBody) > 0 && count(this->message_type = "alt_attachments";
}
}
Returns a formatted header line.
@access private
returns: string
function HeaderLine(value) {
return value .
Returns a formatted mail line.
@access private
returns: string
function TextLine(value) {
return this->LE;
}
//////////////////////////////////////////////
// ATTACHMENT METHODS
//////////////////////////////////////////////
Adds an attachment from a path on the filesystem.
Returns false if the file could not be found
or accessed.
parameter: string name Overrides the attachment name.
parameter: string Encoding).
parameter: string
function AddAttachment(path, encoding = "base64",
path))
{
this->Lang("file_access") . filename = basename(name == "")
filename;
this->attachment);
cur][0] = this->attachment[filename;
cur][2] = this->attachment[encoding;
cur][4] = this->attachment[this->attachment[this->attachment[
Attaches all fs, string, and binary attachments to the message.
Returns an empty string on failure.
@access private
returns: string
function AttachAll() {
// Return text of body
mime = array();
// Add all attachments
for(i < count(i++)
{
// Check for string attachment
this->attachment[bString)
this->attachment[path = i][0];
this->attachment[name = i][2];
this->attachment[type = i][4];
this->attachment[cid = i][7];
this->boundary[1], mime[] = sprintf("Content-Type: \%s; name=\"\%s\"\%s", name, mime[] = sprintf("Content-Transfer-Encoding: \%s\%s", this->LE);
if(mime[] = sprintf("Content-ID: <\%s>\%s", this->LE);
disposition, this->LE.bString)
{
this->EncodeString(encoding);
if(mime[] = this->LE;
}
else
{
this->EncodeFile(encoding);
if(mime[] = this->LE;
}
}
this->boundary[1], mime);
}
Encodes attachment in requested format. Returns an
empty string on failure.
@access private
returns: string
function EncodeFile (encoding = "base64") {
if(!@path, "rb"))
{
this->Lang("file_open") . magic_quotes = get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
fd, filesize(file_buffer = file_buffer, fd);
set_magic_quotes_runtime(file_buffer;
}
Encodes string to requested format. Returns an
empty string on failure.
@access private
returns: string
function EncodeString (encoding = "base64") {
encoding)) {
case "base64":
// chunk_split is found in PHP >= 3.0.6
str), 76, encoded = str);
if (substr(this->LE))) != encoded .= encoded = encoded = str);
break;
default:
this->Lang("encoding") . encoded;
}
Encode a header string to best of Q, B, quoted or none.
@access private
returns: string
function EncodeHeader (position = 'text') {
position)) {
case 'phrase':
if (!preg_match('/[\200-\377]/', encoded = addcslashes(str == %&\'*+\/=?^_`{|}~ -]/', encoded);
else
return ("\"x = preg_match_all('/[^\040\041\043-\133\135-\176]/', matches);
break;
case 'comment':
str, x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', matches);
break;
}
if (str);
this->CharSet);
// Try to select the encoding which should produce the shortest output
if (strlen(x) {
encoded = base64_encode(maxlen -= encoded = trim(chunk_split(maxlen, "\n"));
} else {
encoded = str, encoded = encoded, encoded = str_replace("=".encoded));
}
/m', " =?".encoding?\\1?=", encoded = trim(str_replace("\n", encoded));
return
Encode string to quoted-printable.
@access private
returns: string
function EncodeQP (str) {
this->FixEOL(encoded, -(strlen(this->LE)
this->LE;
// Replace every high ascii, control and = characters
encoded);
// Replace every spaces and tabs when it's the last character on a line
this->LE."/e",
"'='.sprintf('%02X', ord('\\1')).'".encoded);
// Maximum line length of 76 characters before CRLF (74 + space + '=')
this->WrapText(encoded;
}
Encode string to q encoding.
@access private
returns: string
function EncodeQ (position = "text") {
// There should not be any EOL in the string
str);
switch (strtolower(encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
"'='.sprintf('%02X', ord('\\1'))", encoded = str_replace(" ", "_", encoded;
}
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.
parameter: string filename Name of the attachment.
parameter: string Encoding).
parameter: string
function AddStringAttachment(string, encoding = "base64",
attachment array
this->attachment);
cur][0] = this->attachment[filename;
cur][2] = this->attachment[encoding;
cur][4] = this->attachment[this->attachment[this->attachment[
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
use "image/gif".
parameter: string cid Content ID of the attachment. Use this to identify
the Id for accessing the image in an HTML form.
parameter: string encoding File encoding (see type File extension (MIME) type.
returns: bool
function AddEmbeddedImage(cid, encoding = "base64",
path))
{
this->Lang("file_access") . filename = basename(name == "")
filename;
// Append to
cur = count(this->attachment[path;
cur][1] = this->attachment[name;
cur][3] = this->attachment[type;
cur][5] = false; // isStringAttachment
cur][6] = "inline";
cur][7] =
Returns true if an inline attachment is present.
@access private
returns: bool
function InlineImageExists() {
result = false;
for(i < count(i++)
{
if(i][6] == "inline")
{
result;
}
//////////////////////////////////////////////
// MESSAGE RESET METHODS
//////////////////////////////////////////////
Clears all recipients assigned in the TO array. Returns void.
returns: void
function ClearAddresses() {
Clears all recipients assigned in the CC array. Returns void.
returns: void
function ClearCCs() {
this->cc = array();
}
Clears all recipients assigned in the BCC array. Returns void.
returns: void
function ClearBCCs() {
Clears all recipients assigned in the ReplyTo array. Returns void.
returns: void
function ClearReplyTos() {
this->ReplyTo = array();
}
Clears all recipients assigned in the TO, CC and BCC
array. Returns void.
returns: void
function ClearAllRecipients() {
this->cc = array();
Clears all previously set filesystem, string, and binary
attachments. Returns void.
returns: void
function ClearAttachments() {
this->attachment = array();
}
Clears all custom headers. Returns void.
returns: void
function ClearCustomHeaders() {
//////////////////////////////////////////////
// MISCELLANEOUS METHODS
//////////////////////////////////////////////
Adds the error message to the error container.
Returns void.
@access private
returns: void
function SetError(msg) {
this->ErrorInfo =
Returns the proper RFC 822 formatted date.
@access private
returns: string
function RFCDate() {
tz = date("Z");
tz < 0) ? "-" : "+";
tz);
tz/3600)*100 + (result = sprintf("\%s \%s%04d", date("D, j M Y H:i:s"), tz);
return
Returns the appropriate server variable. Should work with both
PHP 4.1.0+ as well as older versions. Returns an empty string
if nothing is found.
@access private
returns: mixed
function ServerVar(varName) {
global HTTP_ENV_VARS;
if(!isset(_SERVER = _SERVER["REMOTE_ADDR"]))
HTTP_ENV_VARS; // must be Apache
}
if(isset(varName]))
return varName];
else
return "";
}
Returns the server hostname or 'localhost.localdomain' if unknown.
@access private
returns: string
function ServerHostname() {
if (result = this->ServerVar('SERVER_NAME') != "")
this->ServerVar('SERVER_NAME');
else
result;
}
Returns a message in the appropriate language.
@access private
returns: string
function Lang(this->language) < 1)
this->language[this->language[key;
}
Returns true if an error occurred.
returns: bool
function IsError() {
return (
Changes every end of line from CR or LF to CRLF.
@access private
returns: string
function FixEOL(str) {
str);
str);
this->LE, str;
}
Adds a custom header.
returns: void
function AddCustomHeader(this->CustomHeader[] = explode(":",
(C) Æliens
20/2/2008
You may not copy or print any of this material without explicit permission of the author or the publisher.
In case of other copyright issues, contact the author.