Zend Framework入门教程之Zend_Mail用法示例
本文实例讲述了ZendFramework入门教程之Zend_Mail用法。分享给大家供大家参考,具体如下:
Zend_Mail组件提供了通用化的功能来创建和发送文本。
Zend_Mail通过PHP内建的mail()函数或者直接通过SMTP连接来发送邮件。
一个简单的邮件由收件人、主题、邮件内容以及发件人等内容组成。
步骤如下
1.创建对象
2.设置邮件内容
3.发送
案例:
<?php
require_once"Zend/Mail.php";
$my_mail=newZend_Mail();//创建一个对象
$my_mail->addTo("jiqing9006@126.com","jim");//添加一个收件人
$my_mail->setSubject("Justatest");//设置主题
$my_mail->setBodyText("HelloJim!");//为邮件设置正文内容
$my_mail->setFrom("706507884@qq.com","jiqing");//为邮件设置发件人
echo"邮件设置完毕";
echo"<p>";
echo"邮件收件人为:";
$result=$my_mail->getHeaders();
echo$result['To'][0];
echo"<p>";
echo"邮件主题为:";
echo$my_mail->getSubject();
echo"<p>";
echo"邮件内容为:";
$result=$my_mail->getBodyText();
echo$result->getContent();
echo"<p>";
echo"邮件发件人为:";
echo$my_mail->getFrom();
echo"<p>";
$my_mail->send();
结果:
邮件设置完毕 邮件收件人为:jim 邮件主题为:Justatest 邮件内容为:HelloJim! 邮件发件人为:706507884@qq.com
Fatalerror:Uncaughtexception'Zend_Mail_Transport_Exception'withmessage'Unabletosendmail.mail()[<ahref='function.mail'>function.mail</a>]:Failedtoconnecttomailserverat"localhost"port25,verifyyour"SMTP"and"smtp_port"settinginphp.inioruseini_set()'inC:\zend\library\Zend\Mail\Transport\Sendmail.php:137Stacktrace:#0C:\zend\library\Zend\Mail\Transport\Abstract.php(348):Zend_Mail_Transport_Sendmail->_sendMail()#1C:\zend\library\Zend\Mail.php(1194):Zend_Mail_Transport_Abstract->send(Object(Zend_Mail))#2D:\xampp\htdocs\test.php(24):Zend_Mail->send()#3{main}throwninC:\zend\library\Zend\Mail\Transport\Sendmail.phponline137
点评:
这里执行不能成功,是因为没有配置好Mail服务器。
源码分析:
<?php
/**
*ZendFramework
*
*LICENSE
*
*ThissourcefileissubjecttothenewBSDlicensethatisbundled
*withthispackageinthefileLICENSE.txt.
*Itisalsoavailablethroughtheworld-wide-webatthisURL:
*http://framework.zend.com/license/new-bsd
*Ifyoudidnotreceiveacopyofthelicenseandareunableto
*obtainitthroughtheworld-wide-web,pleasesendanemail
*tolicense@zend.comsowecansendyouacopyimmediately.
*
*@categoryZend
*@packageZend_Mail
*@copyrightCopyright(c)2005-2012ZendTechnologiesUSAInc.(http://www.zend.com)
*@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense
*@version$Id:Mail.php245932012-01-0520:35:02Zmatthew$
*/
/**
*@seeZend_Mail_Transport_Abstract
*/
require_once'Zend/Mail/Transport/Abstract.php';
/**
*@seeZend_Mime
*/
require_once'Zend/Mime.php';
/**
*@seeZend_Mime_Message
*/
require_once'Zend/Mime/Message.php';
/**
*@seeZend_Mime_Part
*/
require_once'Zend/Mime/Part.php';
/**
*Classforsendinganemail.
*
*@categoryZend
*@packageZend_Mail
*@copyrightCopyright(c)2005-2012ZendTechnologiesUSAInc.(http://www.zend.com)
*@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense
*/
classZend_MailextendsZend_Mime_Message
{
/**#@+
*@accessprotected
*/
/**
*@varZend_Mail_Transport_Abstract
*@static
*/
protectedstatic$_defaultTransport=null;
/**
*@vararray
*@static
*/
protectedstatic$_defaultFrom;
/**
*@vararray
*@static
*/
protectedstatic$_defaultReplyTo;
/**
*Mailcharacterset
*@varstring
*/
protected$_charset='iso-8859-1';
/**
*Mailheaders
*@vararray
*/
protected$_headers=array();
/**
*EncodingofMailheaders
*@varstring
*/
protected$_headerEncoding=Zend_Mime::ENCODING_QUOTEDPRINTABLE;
/**
*From:address
*@varstring
*/
protected$_from=null;
/**
*To:addresses
*@vararray
*/
protected$_to=array();
/**
*Arrayofallrecipients
*@vararray
*/
protected$_recipients=array();
/**
*Reply-Toheader
*@varstring
*/
protected$_replyTo=null;
/**
*Return-Pathheader
*@varstring
*/
protected$_returnPath=null;
/**
*Subject:header
*@varstring
*/
protected$_subject=null;
/**
*Date:header
*@varstring
*/
protected$_date=null;
/**
*Message-ID:header
*@varstring
*/
protected$_messageId=null;
/**
*text/plainMIMEpart
*@varfalse|Zend_Mime_Part
*/
protected$_bodyText=false;
/**
*text/htmlMIMEpart
*@varfalse|Zend_Mime_Part
*/
protected$_bodyHtml=false;
/**
*MIMEboundarystring
*@varstring
*/
protected$_mimeBoundary=null;
/**
*Contenttypeofthemessage
*@varstring
*/
protected$_type=null;
/**#@-*/
/**
*Flag:whetherornotemailhasattachments
*@varboolean
*/
public$hasAttachments=false;
/**
*Setsthedefaultmailtransportforallfollowingusesof
*Zend_Mail::send();
*
*@todoAllowpassingastringtoindicatethetransporttoload
*@todoAllowpassinginoptionaloptionsforthetransporttoload
*@paramZend_Mail_Transport_Abstract$transport
*/
publicstaticfunctionsetDefaultTransport(Zend_Mail_Transport_Abstract$transport)
{
self::$_defaultTransport=$transport;
}
/**
*Getsthedefaultmailtransportforallfollowingusesof
*unittests
*
*@todoAllowpassingastringtoindicatethetransporttoload
*@todoAllowpassinginoptionaloptionsforthetransporttoload
*/
publicstaticfunctiongetDefaultTransport()
{
returnself::$_defaultTransport;
}
/**
*Clearthedefaulttransportproperty
*/
publicstaticfunctionclearDefaultTransport()
{
self::$_defaultTransport=null;
}
/**
*Publicconstructor
*
*@paramstring$charset
*@returnvoid
*/
publicfunction__construct($charset=null)
{
if($charset!=null){
$this->_charset=$charset;
}
}
/**
*Returncharsetstring
*
*@returnstring
*/
publicfunctiongetCharset()
{
return$this->_charset;
}
/**
*Setcontenttype
*
*Shouldonlybeusedformanuallysettingmultipartcontenttypes.
*
*@paramstring$typeContenttype
*@returnZend_MailImplementsfluentinterface
*@throwsZend_Mail_ExceptionfortypesnotsupportedbyZend_Mime
*/
publicfunctionsetType($type)
{
$allowed=array(
Zend_Mime::MULTIPART_ALTERNATIVE,
Zend_Mime::MULTIPART_MIXED,
Zend_Mime::MULTIPART_RELATED,
);
if(!in_array($type,$allowed)){
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('Invalidcontenttype"'.$type.'"');
}
$this->_type=$type;
return$this;
}
/**
*Getcontenttypeofthemessage
*
*@returnstring
*/
publicfunctiongetType()
{
return$this->_type;
}
/**
*Setanarbitrarymimeboundaryforthemessage
*
*Ifnotset,Zend_Mimewillgenerateone.
*
*@paramstring$boundary
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionsetMimeBoundary($boundary)
{
$this->_mimeBoundary=$boundary;
return$this;
}
/**
*Returntheboundarystringusedforthemessage
*
*@returnstring
*/
publicfunctiongetMimeBoundary()
{
return$this->_mimeBoundary;
}
/**
*Returnencodingofmailheaders
*
*@deprecateduse{@linkgetHeaderEncoding()}instead
*@returnstring
*/
publicfunctiongetEncodingOfHeaders()
{
return$this->getHeaderEncoding();
}
/**
*Returntheencodingofmailheaders
*
*EitherZend_Mime::ENCODING_QUOTEDPRINTABLEorZend_Mime::ENCODING_BASE64
*
*@returnstring
*/
publicfunctiongetHeaderEncoding()
{
return$this->_headerEncoding;
}
/**
*Settheencodingofmailheaders
*
*@deprecatedUse{@linksetHeaderEncoding()}instead.
*@paramstring$encoding
*@returnZend_Mail
*/
publicfunctionsetEncodingOfHeaders($encoding)
{
return$this->setHeaderEncoding($encoding);
}
/**
*Settheencodingofmailheaders
*
*@paramstring$encodingZend_Mime::ENCODING_QUOTEDPRINTABLEorZend_Mime::ENCODING_BASE64
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionsetHeaderEncoding($encoding)
{
$allowed=array(
Zend_Mime::ENCODING_BASE64,
Zend_Mime::ENCODING_QUOTEDPRINTABLE
);
if(!in_array($encoding,$allowed)){
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('Invalidencoding"'.$encoding.'"');
}
$this->_headerEncoding=$encoding;
return$this;
}
/**
*Setsthetextbodyforthemessage.
*
*@paramstring$txt
*@paramstring$charset
*@paramstring$encoding
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionsetBodyText($txt,$charset=null,$encoding=Zend_Mime::ENCODING_QUOTEDPRINTABLE)
{
if($charset===null){
$charset=$this->_charset;
}
$mp=newZend_Mime_Part($txt);
$mp->encoding=$encoding;
$mp->type=Zend_Mime::TYPE_TEXT;
$mp->disposition=Zend_Mime::DISPOSITION_INLINE;
$mp->charset=$charset;
$this->_bodyText=$mp;
return$this;
}
/**
*ReturntextbodyZend_Mime_Partorstring
*
*@parambooltextOnlyWhethertoreturnjustthebodytextcontentortheMIMEpart;defaultstofalse,theMIMEpart
*@returnfalse|Zend_Mime_Part|string
*/
publicfunctiongetBodyText($textOnly=false)
{
if($textOnly&&$this->_bodyText){
$body=$this->_bodyText;
return$body->getContent();
}
return$this->_bodyText;
}
/**
*SetstheHTMLbodyforthemessage
*
*@paramstring$html
*@paramstring$charset
*@paramstring$encoding
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionsetBodyHtml($html,$charset=null,$encoding=Zend_Mime::ENCODING_QUOTEDPRINTABLE)
{
if($charset===null){
$charset=$this->_charset;
}
$mp=newZend_Mime_Part($html);
$mp->encoding=$encoding;
$mp->type=Zend_Mime::TYPE_HTML;
$mp->disposition=Zend_Mime::DISPOSITION_INLINE;
$mp->charset=$charset;
$this->_bodyHtml=$mp;
return$this;
}
/**
*ReturnZend_Mime_PartrepresentingbodyHTML
*
*@parambool$htmlOnlyWhethertoreturnthebodyHTMLonly,ortheMIMEpart;defaultstofalse,theMIMEpart
*@returnfalse|Zend_Mime_Part|string
*/
publicfunctiongetBodyHtml($htmlOnly=false)
{
if($htmlOnly&&$this->_bodyHtml){
$body=$this->_bodyHtml;
return$body->getContent();
}
return$this->_bodyHtml;
}
/**
*Addsanexistingattachmenttothemailmessage
*
*@paramZend_Mime_Part$attachment
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionaddAttachment(Zend_Mime_Part$attachment)
{
$this->addPart($attachment);
$this->hasAttachments=true;
return$this;
}
/**
*CreatesaZend_Mime_Partattachment
*
*Attachmentisautomaticallyaddedtothemailobjectaftercreation.The
*attachmentobjectisreturnedtoallowforfurthermanipulation.
*
*@paramstring$body
*@paramstring$mimeType
*@paramstring$disposition
*@paramstring$encoding
*@paramstring$filenameOPTIONALAfilenamefortheattachment
*@returnZend_Mime_PartNewlycreatedZend_Mime_Partobject(toallow
*advancedsettings)
*/
publicfunctioncreateAttachment($body,
$mimeType=Zend_Mime::TYPE_OCTETSTREAM,
$disposition=Zend_Mime::DISPOSITION_ATTACHMENT,
$encoding=Zend_Mime::ENCODING_BASE64,
$filename=null)
{
$mp=newZend_Mime_Part($body);
$mp->encoding=$encoding;
$mp->type=$mimeType;
$mp->disposition=$disposition;
$mp->filename=$filename;
$this->addAttachment($mp);
return$mp;
}
/**
*Returnacountofmessageparts
*
*@returninteger
*/
publicfunctiongetPartCount()
{
returncount($this->_parts);
}
/**
*Encodeheaderfields
*
*EncodesheadercontentaccordingtoRFC1522ifitcontainsnon-printable
*characters.
*
*@paramstring$value
*@returnstring
*/
protectedfunction_encodeHeader($value)
{
if(Zend_Mime::isPrintable($value)===false){
if($this->getHeaderEncoding()===Zend_Mime::ENCODING_QUOTEDPRINTABLE){
$value=Zend_Mime::encodeQuotedPrintableHeader($value,$this->getCharset(),Zend_Mime::LINELENGTH,Zend_Mime::LINEEND);
}else{
$value=Zend_Mime::encodeBase64Header($value,$this->getCharset(),Zend_Mime::LINELENGTH,Zend_Mime::LINEEND);
}
}
return$value;
}
/**
*Addaheadertothemessage
*
*Addsaheadertothismessage.Ifappendistrueandtheheaderalready
*exists,raisesaflagindicatingthattheheadershouldbeappended.
*
*@paramstring$headerName
*@paramstring$value
*@parambool$append
*/
protectedfunction_storeHeader($headerName,$value,$append=false)
{
if(isset($this->_headers[$headerName])){
$this->_headers[$headerName][]=$value;
}else{
$this->_headers[$headerName]=array($value);
}
if($append){
$this->_headers[$headerName]['append']=true;
}
}
/**
*Clearheaderfromthemessage
*
*@paramstring$headerName
*@deprecatedusepublicmethoddirectly
*/
protectedfunction_clearHeader($headerName)
{
$this->clearHeader($headerName);
}
/**
*Helperfunctionforaddingarecipientandthecorrespondingheader
*
*@paramstring$headerName
*@paramstring$email
*@paramstring$name
*/
protectedfunction_addRecipientAndHeader($headerName,$email,$name)
{
$email=$this->_filterEmail($email);
$name=$this->_filterName($name);
//preventduplicates
$this->_recipients[$email]=1;
$this->_storeHeader($headerName,$this->_formatAddress($email,$name),true);
}
/**
*AddsTo-headerandrecipient,$emailcanbeanarray,orasinglestringaddress
*
*@paramstring|array$email
*@paramstring$name
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionaddTo($email,$name='')
{
if(!is_array($email)){
$email=array($name=>$email);
}
foreach($emailas$n=>$recipient){
$this->_addRecipientAndHeader('To',$recipient,is_int($n)?'':$n);
$this->_to[]=$recipient;
}
return$this;
}
/**
*AddsCc-headerandrecipient,$emailcanbeanarray,orasinglestringaddress
*
*@paramstring|array$email
*@paramstring$name
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionaddCc($email,$name='')
{
if(!is_array($email)){
$email=array($name=>$email);
}
foreach($emailas$n=>$recipient){
$this->_addRecipientAndHeader('Cc',$recipient,is_int($n)?'':$n);
}
return$this;
}
/**
*AddsBccrecipient,$emailcanbeanarray,orasinglestringaddress
*
*@paramstring|array$email
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionaddBcc($email)
{
if(!is_array($email)){
$email=array($email);
}
foreach($emailas$recipient){
$this->_addRecipientAndHeader('Bcc',$recipient,'');
}
return$this;
}
/**
*Returnlistofrecipientemailaddresses
*
*@returnarray(ofstrings)
*/
publicfunctiongetRecipients()
{
returnarray_keys($this->_recipients);
}
/**
*Clearheaderfromthemessage
*
*@paramstring$headerName
*@returnZend_MailProvidesfluentinter
*/
publicfunctionclearHeader($headerName)
{
if(isset($this->_headers[$headerName])){
unset($this->_headers[$headerName]);
}
return$this;
}
/**
*Clearslistofrecipientemailaddresses
*
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionclearRecipients()
{
$this->_recipients=array();
$this->_to=array();
$this->clearHeader('To');
$this->clearHeader('Cc');
$this->clearHeader('Bcc');
return$this;
}
/**
*SetsFrom-headerandsenderofthemessage
*
*@paramstring$email
*@paramstring$name
*@returnZend_MailProvidesfluentinterface
*@throwsZend_Mail_Exceptionifcalledsubsequenttimes
*/
publicfunctionsetFrom($email,$name=null)
{
if(null!==$this->_from){
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('FromHeadersettwice');
}
$email=$this->_filterEmail($email);
$name=$this->_filterName($name);
$this->_from=$email;
$this->_storeHeader('From',$this->_formatAddress($email,$name),true);
return$this;
}
/**
*SetReply-ToHeader
*
*@paramstring$email
*@paramstring$name
*@returnZend_Mail
*@throwsZend_Mail_Exceptionifcalledmorethanonetime
*/
publicfunctionsetReplyTo($email,$name=null)
{
if(null!==$this->_replyTo){
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('Reply-ToHeadersettwice');
}
$email=$this->_filterEmail($email);
$name=$this->_filterName($name);
$this->_replyTo=$email;
$this->_storeHeader('Reply-To',$this->_formatAddress($email,$name),true);
return$this;
}
/**
*Returnsthesenderofthemail
*
*@returnstring
*/
publicfunctiongetFrom()
{
return$this->_from;
}
/**
*ReturnsthecurrentReply-Toaddressofthemessage
*
*@returnstring|nullReply-Toaddress,nullwhennotset
*/
publicfunctiongetReplyTo()
{
return$this->_replyTo;
}
/**
*Clearsthesenderfromthemail
*
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionclearFrom()
{
$this->_from=null;
$this->clearHeader('From');
return$this;
}
/**
*ClearsthecurrentReply-Toaddressfromthemessage
*
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionclearReplyTo()
{
$this->_replyTo=null;
$this->clearHeader('Reply-To');
return$this;
}
/**
*SetsDefaultFrom-emailandnameofthemessage
*
*@paramstring$email
*@paramstringOptional$name
*@returnvoid
*/
publicstaticfunctionsetDefaultFrom($email,$name=null)
{
self::$_defaultFrom=array('email'=>$email,'name'=>$name);
}
/**
*Returnsthedefaultsenderofthemail
*
*@returnnull|arrayNullifnonewasset.
*/
publicstaticfunctiongetDefaultFrom()
{
returnself::$_defaultFrom;
}
/**
*Clearsthedefaultsenderfromthemail
*
*@returnvoid
*/
publicstaticfunctionclearDefaultFrom()
{
self::$_defaultFrom=null;
}
/**
*SetsFrom-nameand-emailbasedonthedefaults
*
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionsetFromToDefaultFrom(){
$from=self::getDefaultFrom();
if($from===null){
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception(
'NodefaultFromAddresssettouse');
}
$this->setFrom($from['email'],$from['name']);
return$this;
}
/**
*SetsDefaultReplyTo-addressand-nameofthemessage
*
*@paramstring$email
*@paramstringOptional$name
*@returnvoid
*/
publicstaticfunctionsetDefaultReplyTo($email,$name=null)
{
self::$_defaultReplyTo=array('email'=>$email,'name'=>$name);
}
/**
*ReturnsthedefaultReply-ToAddressandNameofthemail
*
*@returnnull|arrayNullifnonewasset.
*/
publicstaticfunctiongetDefaultReplyTo()
{
returnself::$_defaultReplyTo;
}
/**
*ClearsthedefaultReplyTo-addressand-namefromthemail
*
*@returnvoid
*/
publicstaticfunctionclearDefaultReplyTo()
{
self::$_defaultReplyTo=null;
}
/**
*SetsReplyTo-nameand-emailbasedonthedefaults
*
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionsetReplyToFromDefault(){
$replyTo=self::getDefaultReplyTo();
if($replyTo===null){
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception(
'NodefaultReply-ToAddresssettouse');
}
$this->setReplyTo($replyTo['email'],$replyTo['name']);
return$this;
}
/**
*SetstheReturn-Pathheaderofthemessage
*
*@paramstring$email
*@returnZend_MailProvidesfluentinterface
*@throwsZend_Mail_Exceptionifsetmultipletimes
*/
publicfunctionsetReturnPath($email)
{
if($this->_returnPath===null){
$email=$this->_filterEmail($email);
$this->_returnPath=$email;
$this->_storeHeader('Return-Path',$email,false);
}else{
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('Return-PathHeadersettwice');
}
return$this;
}
/**
*ReturnsthecurrentReturn-Pathaddressofthemessage
*
*IfnoReturn-Pathheaderisset,returnsthevalueof{@link$_from}.
*
*@returnstring
*/
publicfunctiongetReturnPath()
{
if(null!==$this->_returnPath){
return$this->_returnPath;
}
return$this->_from;
}
/**
*ClearsthecurrentReturn-Pathaddressfromthemessage
*
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionclearReturnPath()
{
$this->_returnPath=null;
$this->clearHeader('Return-Path');
return$this;
}
/**
*Setsthesubjectofthemessage
*
*@paramstring$subject
*@returnZend_MailProvidesfluentinterface
*@throwsZend_Mail_Exception
*/
publicfunctionsetSubject($subject)
{
if($this->_subject===null){
$subject=$this->_filterOther($subject);
$this->_subject=$this->_encodeHeader($subject);
$this->_storeHeader('Subject',$this->_subject);
}else{
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('Subjectsettwice');
}
return$this;
}
/**
*Returnstheencodedsubjectofthemessage
*
*@returnstring
*/
publicfunctiongetSubject()
{
return$this->_subject;
}
/**
*Clearstheencodedsubjectfromthemessage
*
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionclearSubject()
{
$this->_subject=null;
$this->clearHeader('Subject');
return$this;
}
/**
*SetsDate-header
*
*@paramtimestamp|string|Zend_Date$date
*@returnZend_MailProvidesfluentinterface
*@throwsZend_Mail_Exceptionifcalledsubsequenttimesorwrongdateformat.
*/
publicfunctionsetDate($date=null)
{
if($this->_date===null){
if($date===null){
$date=date('r');
}elseif(is_int($date)){
$date=date('r',$date);
}elseif(is_string($date)){
$date=strtotime($date);
if($date===false||$date<0){
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('StringrepresentationsofDateHeadermustbe'.
'strtotime()-compatible');
}
$date=date('r',$date);
}elseif($dateinstanceofZend_Date){
$date=$date->get(Zend_Date::RFC_2822);
}else{
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception(__METHOD__.'onlyacceptsUNIXtimestamps,Zend_Dateobjects,'.
'andstrtotime()-compatiblestrings');
}
$this->_date=$date;
$this->_storeHeader('Date',$date);
}else{
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('DateHeadersettwice');
}
return$this;
}
/**
*Returnstheformatteddateofthemessage
*
*@returnstring
*/
publicfunctiongetDate()
{
return$this->_date;
}
/**
*Clearstheformatteddatefromthemessage
*
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionclearDate()
{
$this->_date=null;
$this->clearHeader('Date');
return$this;
}
/**
*SetstheMessage-IDofthemessage
*
*@paramboolean|string$id
*true:Auto
*false:Noset
*null:Noset
*string:Setsgivenstring(Anglebracketsisnotnecessary)
*@returnZend_MailProvidesfluentinterface
*@throwsZend_Mail_Exception
*/
publicfunctionsetMessageId($id=true)
{
if($id===null||$id===false){
return$this;
}elseif($id===true){
$id=$this->createMessageId();
}
if($this->_messageId===null){
$id=$this->_filterOther($id);
$this->_messageId=$id;
$this->_storeHeader('Message-Id','<'.$this->_messageId.'>');
}else{
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('Message-IDsettwice');
}
return$this;
}
/**
*ReturnstheMessage-IDofthemessage
*
*@returnstring
*/
publicfunctiongetMessageId()
{
return$this->_messageId;
}
/**
*ClearstheMessage-IDfromthemessage
*
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionclearMessageId()
{
$this->_messageId=null;
$this->clearHeader('Message-Id');
return$this;
}
/**
*CreatestheMessage-ID
*
*@returnstring
*/
publicfunctioncreateMessageId(){
$time=time();
if($this->_from!==null){
$user=$this->_from;
}elseif(isset($_SERVER['REMOTE_ADDR'])){
$user=$_SERVER['REMOTE_ADDR'];
}else{
$user=getmypid();
}
$rand=mt_rand();
if($this->_recipients!==array()){
$recipient=array_rand($this->_recipients);
}else{
$recipient='unknown';
}
if(isset($_SERVER["SERVER_NAME"])){
$hostName=$_SERVER["SERVER_NAME"];
}else{
$hostName=php_uname('n');
}
returnsha1($time.$user.$rand.$recipient).'@'.$hostName;
}
/**
*Addacustomheadertothemessage
*
*@paramstring$name
*@paramstring$value
*@paramboolean$append
*@returnZend_MailProvidesfluentinterface
*@throwsZend_Mail_Exceptiononattemptstocreatestandardheaders
*/
publicfunctionaddHeader($name,$value,$append=false)
{
$prohibit=array('to','cc','bcc','from','subject',
'reply-to','return-path',
'date','message-id',
);
if(in_array(strtolower($name),$prohibit)){
/**
*@seeZend_Mail_Exception
*/
require_once'Zend/Mail/Exception.php';
thrownewZend_Mail_Exception('CannotsetstandardheaderfromaddHeader()');
}
$value=$this->_filterOther($value);
$value=$this->_encodeHeader($value);
$this->_storeHeader($name,$value,$append);
return$this;
}
/**
*Returnmailheaders
*
*@returnvoid
*/
publicfunctiongetHeaders()
{
return$this->_headers;
}
/**
*Sendsthisemailusingthegiventransportorapreviously
*setDefaultTransportortheinternalmailfunctionifno
*defaulttransporthadbeenset.
*
*@paramZend_Mail_Transport_Abstract$transport
*@returnZend_MailProvidesfluentinterface
*/
publicfunctionsend($transport=null)
{
if($transport===null){
if(!self::$_defaultTransportinstanceofZend_Mail_Transport_Abstract){
require_once'Zend/Mail/Transport/Sendmail.php';
$transport=newZend_Mail_Transport_Sendmail();
}else{
$transport=self::$_defaultTransport;
}
}
if($this->_date===null){
$this->setDate();
}
if(null===$this->_from&&null!==self::getDefaultFrom()){
$this->setFromToDefaultFrom();
}
if(null===$this->_replyTo&&null!==self::getDefaultReplyTo()){
$this->setReplyToFromDefault();
}
$transport->send($this);
return$this;
}
/**
*Filterofemaildata
*
*@paramstring$email
*@returnstring
*/
protectedfunction_filterEmail($email)
{
$rule=array("\r"=>'',
"\n"=>'',
"\t"=>'',
'"'=>'',
','=>'',
'<'=>'',
'>'=>'',
);
returnstrtr($email,$rule);
}
/**
*Filterofnamedata
*
*@paramstring$name
*@returnstring
*/
protectedfunction_filterName($name)
{
$rule=array("\r"=>'',
"\n"=>'',
"\t"=>'',
'"'=>"'",
'<'=>'[',
'>'=>']',
);
returntrim(strtr($name,$rule));
}
/**
*Filterofotherdata
*
*@paramstring$data
*@returnstring
*/
protectedfunction_filterOther($data)
{
$rule=array("\r"=>'',
"\n"=>'',
"\t"=>'',
);
returnstrtr($data,$rule);
}
/**
*Formatse-mailaddress
*
*@paramstring$email
*@paramstring$name
*@returnstring
*/
protectedfunction_formatAddress($email,$name)
{
if($name===''||$name===null||$name===$email){
return$email;
}else{
$encodedName=$this->_encodeHeader($name);
if($encodedName===$name&&strcspn($name,'()<>[]:;@\\,')!=strlen($name)){
$format='"%s"<%s>';
}else{
$format='%s<%s>';
}
returnsprintf($format,$encodedName,$email);
}
}
}
更多关于zend相关内容感兴趣的读者可查看本站专题:《ZendFrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于ZendFramework框架的PHP程序设计有所帮助。