标题: php邮件类比较实用,推荐给大家使用 [打印本页] 作者: tznktg 时间: 2007-10-5 16:01 标题: php邮件类比较实用,推荐给大家使用 <?php
////////////////////////////////////////////////////
// phpmailer - PHP email class
//
// Version 1.60, Created 03/30/2002
//
// Class for sending email using either
// sendmail, PHP mail(), or SMTP. Methods are
// based upon the standard AspEmail(tm) classes.
///
// License: LGPL, see LICENSE
////////////////////////////////////////////////////
/**
* phpmailer - PHP email transport class
* @author Brent R. Matzelle
*/
class phpmailer
{
/////////////////////////////////////////////////
// PUBLIC VARIABLES
/////////////////////////////////////////////////
/**
* Email priority (1 = High, 3 = Normal, 5 = low). Default value is 3.
* @public
* @type int
*/
var $Priority = 3;
/**
* Sets the CharSet of the message. Default value is "iso-8859-1".
* @public
* @type string
*/
var $CharSet = "iso-8859-1";
/**
* Sets the Content-type of the message. Default value is "text/plain".
* @public
* @type string
*/
var $ContentType = "text/plain"; //plain:无格式
/**
* Sets the Encoding of the message. Options for this are "8bit" (default),
* "7bit", "binary", "base64", and "quoted-printable".
* @public
* @type string
*/
var $Encoding = "8bit";
/**
* Holds the most recent mailer error message. Default value is "".
* @public
* @type string
*/
var $ErrorInfo = "";
/**
* Sets the From email address for the message. Default value is "root@localhost".
* @public
* @type string
*/
var $From = "root@localhost";
/**
* Sets the From name of the message. Default value is "Root User".
* @public
* @type string
*/
var $FromName = "Root User";
/**
* Sets the Sender email of the message. If not empty, will be sent via -f to sendmail
* or as 'MAIL FROM' in smtp mode. Default value is "".
* @public
* @type string
*/
var $Sender = "";
/**
* Sets the Subject of the message. Default value is "".
* @public
* @type string
*/
var $Subject = "";
/**
* Sets the Body of the message. This can be either an HTML or text body.
* If HTML then run IsHTML(true). Default value is "".
* @public
* @type 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.
* Default value is "".
* @public
* @type string
*/
var $AltBody = "";
/**
* Sets word wrapping on the body of the message to a given number of
* characters. Default value is 0 (off).
* @public
* @type int
*/
var $WordWrap = 0;
/**
* Method to send mail: ("mail", "sendmail", or "smtp").
* Default value is "mail".
* @public
* @type string
*/
var $Mailer = "mail";
/**
* Sets the path of the sendmail program. Default value is
* "/usr/sbin/sendmail".
* @public
* @type string
*/
var $Sendmail = "/usr/sbin/sendmail";
/**
* Turns Microsoft mail client headers on and off. Useful mostly
* for older clients. Default value is false (off).
* @public
* @type bool
*/
var $UseMSMailHeaders = false;
/**
* Path to phpmailer plugins. This is now only useful if the SMTP class
* is in a different directory than the PHP include path.
* Default is empty ("").
* @public
* @type string
*/
var $PluginDir = "";
/**
* 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.domain.com:25;smtp2.domain.com").
* Hosts will be tried in order.
* Default value is "localhost".
* @public
* @type string
*/
var $Host = "localhost";
/**
* Sets the default SMTP server port. Default value is 25.
* @public
* @type int
*/
var $Port = 25;
/**
* Sets the SMTP HELO of the message.
* Default value is "localhost.localdomain".
* @public
* @type string
*/
var $Helo = "localhost.localdomain";
/**
* Sets SMTP authentication. Utilizes the Username and Password variables.
* Default value is false (off).
* @public
* @type bool
*/
var $SMTPAuth = false;
/**
* Sets SMTP username. Default value is "".
* @public
* @type string
*/
var $Username = "";
/**
* Sets SMTP password. Default value is "".
* @public
* @type string
*/
var $Password = "";
/**
* Sets the SMTP server timeout in seconds. This function will not
* work with the win32 version. Default value is 10.
* @public
* @type int
*/
var $Timeout = 10;
/**
* Sets SMTP class debugging on or off. Default value is false (off).
* @public
* @type bool
*/
var $SMTPDebug = false;
/**
* Adds a "Cc" address. Note: this function works
* with the SMTP mailer on win32, not with the "mail"
* mailer. This is a PHP bug that has been submitted
* on http://bugs.php.net. The *NIX version of PHP
* functions correctly. Returns void.
* @public
* @returns void
*/
function AddCC($address, $name = "") {
$cur = count($this->cc);
$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"
* mailer. This is a PHP bug that has been submitted
* on http://bugs.php.net. The *NIX version of PHP
* functions correctly.
* Returns void.
* @public
* @returns void
*/
function AddBCC($address, $name = "") {
$cur = count($this->bcc);
$this->bcc[$cur][0] = trim($address);
$this->bcc[$cur][1] = $name;
}
/////////////////////////////////////////////////
// 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.
* @public
* @returns bool
*/
function Send() {
$header = "";
$body = "";
if((count($this->to) + count($this->cc) + count($this->bcc)) < 1)
{
$this->error_handler("You must provide at least one recipient email address");
return false;
}
// Set whether the message is multipart/alternative
if(!empty($this->AltBody))
$this->ContentType = "multipart/alternative";
// Attach sender information & date
$header = $this->received();
$header .= sprintf("Date: %s%s", $this->rfc_date(), $this->LE);
$header .= $this->create_header();
/**
* Sends mail message to an assigned queue directory. Has an optional
* sendTime argument. This is used when the user wants the
* message to be sent from the queue at a predetermined time.
* The data must be a valid timestamp like that returned from
* the time() or strtotime() functions. Returns false on failure
* or the message file name if success.
* @public
* @returns string
*/
function SendToQueue($queue_path, $send_time = 0) {
$message = array();
$header = "";
$body = "";
// If invalid or empty just set to the current time
if($send_time == 0)
$send_time = time();
if(!is_dir($queue_path))
{
$this->error_handler("The supplied queue directory does not exist");
return false;
}
if((count($this->to) + count($this->cc) + count($this->bcc)) < 1)
{
$this->error_handler("You must provide at least one recipient email address");
return false;
}
// Set whether the message is multipart/alternative
if(!empty($this->AltBody))
$this->ContentType = "multipart/alternative";
if ($this->Sender != "" && PHP_VERSION >= "4.0.5")
{
// The fifth parameter to mail is only available in PHP >= 4.0.5
$params = sprintf("-oi -f %s", $this->Sender);
$rt = @mail($to, $this->Subject, $body, $header, $params);
}
else
{
$rt = @mail($to, $this->Subject, $body, $header);
}
if (isset($old_from))
ini_set("sendmail_from", $old_from);
if(!$rt)
{
$this->error_handler("Could not instantiate mail()");
return false;
}
return true;
}
/**
* Sends mail via SMTP using PhpSMTP (Author:
* Chris Ryan). Returns bool. Returns false if there is a
* bad MAIL FROM, RCPT, or DATA input.
* @private
* @returns bool
*/
function smtp_send($header, $body) {
// Include SMTP class code, but not twice
include_once($this->PluginDir . "class.smtp.php");
$smtp = new SMTP;
$smtp->do_debug = $this->SMTPDebug;
// Try to connect to all SMTP servers
$hosts = explode(";", $this->Host);
$index = 0;
$connection = false;
$smtp_from = "";
$bad_rcpt = array();
$e = "";
// Retry while there is no connection
while($index < count($hosts) && $connection == false)
{
if(strstr($hosts[$index], ":"))
list($host, $port) = explode(":", $hosts[$index]);
else
{
$host = $hosts[$index];
$port = $this->Port;
}
if($smtp->Connect($host, $port, $this->Timeout))
$connection = true;
//printf("%s host could not connect<br>", $hosts[$index]); //debug only
$index++;
}
if(!$connection)
{
$this->error_handler("SMTP Error: could not connect to SMTP host server(s)");
return false;
}
// Must perform HELO before authentication
$smtp->Hello($this->Helo);
// If user requests SMTP authentication
if($this->SMTPAuth)
{
if(!$smtp->Authenticate($this->Username, $this->Password))
{
$this->error_handler("SMTP Error: Could not authenticate");
return false;
}
}
/**
* Wraps message for use with mailers that do not
* automatically perform wrapping and for quoted-printable.
* Original written by philippe. Returns string.
* @private
* @returns string
*/
function word_wrap($message, $length, $qp_mode = false) {
if ($qp_mode)
$soft_break = sprintf(" =%s", $this->LE);
else
$soft_break = $this->LE;
// No additional lines when using mail() function
if($this->Mailer != "mail")
$header[] = $this->LE.$this->LE;
return(join("", $header));
}
/**
* Assembles the message body. Returns a string if successful
* or false if unsuccessful.
* @private
* @returns string
*/
function create_body() {
$body = array();
// wordwrap the message body if set
if($this->WordWrap > 0)
$this->Body = $this->word_wrap($this->Body, $this->WordWrap);
switch($this->message_type)
{
case "alt":
// Return text of body
$bndry = new Boundary($this->boundary[1]);
$bndry->CharSet = $this->CharSet;
$bndry->Encoding = $this->Encoding;
$body[] = $bndry->GetSource();
/**
* Adds an attachment from a path on the filesystem.
* Checks if attachment is valid and then adds
* the attachment to the list.
* Returns false if the file could not be found
* or accessed.
* @public
* @returns bool
*/
function AddAttachment($path, $name = "", $encoding = "base64", $type = "application/octet-stream") {
if(!@is_file($path))
{
$this->error_handler(sprintf("Could not access [%s] file", $path));
return false;
}
/**
* Attaches all fs, string, and binary attachments to the message.
* Returns a string if successful or false if unsuccessful.
* @private
* @returns string
*/
function attach_all() {
// Return text of body
$mime = array();
/**
* Encodes attachment in requested format. Returns a
* string if successful or false if unsuccessful.
* @private
* @returns string
*/
function encode_file ($path, $encoding = "base64") {
if(!@$fd = fopen($path, "rb"))
{
$this->error_handler(sprintf("File Error: Could not open file %s", $path));
return false;
}
$file = fread($fd, filesize($path));
$encoded = $this->encode_string($file, $encoding);
fclose($fd);
return($encoded);
}
/**
* Encodes string to requested format. Returns a
* string if successful or false if unsuccessful.
* @private
* @returns string
*/
function encode_string ($str, $encoding = "base64") {
switch(strtolower($encoding)) {
case "base64":
// chunk_split is found in PHP >= 3.0.6
$encoded = chunk_split(base64_encode($str));
break;
case "7bit":
case "8bit":
$encoded = $this->fix_eol($str);
if (substr($encoded, -2) != $this->LE)
$encoded .= $this->LE;
break;
case "binary":
$encoded = $str;
break;
case "quoted-printable":
$encoded = $this->encode_qp($str);
break;
/**
* Encode string to quoted-printable. Returns a string.
* @private
* @returns string
*/
function encode_qp ($str) {
$encoded = $this->fix_eol($str);
if (substr($encoded, -2) != $this->LE)
$encoded .= $this->LE;
// Replace every high ascii, control and = characters
$encoded = preg_replace("/([\001-\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
$encoded = preg_replace("/([\011\040])".$this->LE."/e",
"'='.sprintf('%02X', ord('\\1')).'".$this->LE."'", $encoded);
// Maximum line length of 76 characters before CRLF (74 + space + '=')
$encoded = $this->word_wrap($encoded, 74, true);
return $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.
* @public
* @returns void
*/
function AddStringAttachment($string, $filename, $encoding = "base64", $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.
* @param cid this is the Content Id of the attachment. Use this to identify
* the Id for accessing the image in an HTML form.
* @public
* @returns bool
*/
function AddEmbeddedImage($path, $cid, $name = "", $encoding = "base64", $type = "application/octet-stream") {
/**
* Clears all recipients assigned in the TO array. Returns void.
* @public
* @returns void
*/
function ClearAddresses() {
$this->to = array();
}
/**
* Clears all recipients assigned in the CC array. Returns void.
* @public
* @returns void
*/
function ClearCCs() {
$this->cc = array();
}
/**
* Clears all recipients assigned in the BCC array. Returns void.
* @public
* @returns void
*/
function ClearBCCs() {
$this->bcc = array();
}
/**
* Clears all recipients assigned in the ReplyTo array. Returns void.
* @public
* @returns void
*/
function ClearReplyTos() {
$this->ReplyTo = array();
}
/**
* Clears all recipients assigned in the TO, CC and BCC
* array. Returns void.
* @public
* @returns void
*/
function ClearAllRecipients() {
$this->to = array();
$this->cc = array();
$this->bcc = array();
}
/**
* Clears all previously set filesystem, string, and binary
* attachments. Returns void.
* @public
* @returns void
*/
function ClearAttachments() {
$this->attachment = array();
}
/**
* Returns received header for message tracing. Returns string.
* @private
* @returns string
*/
function received() {
// Check for vars because they might not exist. Possibly
// write a small retrieval function (that mailer can use too!)
$str = sprintf("Received: from phpmailer ([%s]) by %s " .
"with HTTP;%s\t %s%s",
$this->get_server_var("REMOTE_ADDR"),
$this->get_server_var("SERVER_NAME"),
$this->LE,
$this->rfc_date(),
$this->LE);
return $str;
}
/**
* 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.
* @private
* @returns mixed
*/
function get_server_var($varName) {
global $HTTP_SERVER_VARS;
global $HTTP_ENV_VARS;
if(!isset($_SERVER))
{
$_SERVER = $HTTP_SERVER_VARS;
if(!isset($_SERVER["REMOTE_ADDR"]))
$_SERVER = $HTTP_ENV_VARS; // must be Apache
}
// 附加内容
//$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
//$mail->Send()为邮件发送函数,不成功时执行if内容
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>