Вы находитесь на странице: 1из 16

9/30/2016

PHPMailertutorial

AskApacheWebDevelopmentFREETHOUGHTFREESOFTWAREFREEWORLD(http://www.fsf.org/register_form?referrer=7511)
Skip
HomePHPPHPMailertutorial
PHPMailertutorial
SpeedUpSiteswithhtaccessCachingLFTtraceroutetool
byCharlesTorvalds56comments
ThisismeanttobeanimprovedversionofthearticlewrittenbyPHPFreaksfounder,EricRosebrockonthePHPFreaks
(http://www.phpfreaks.com/)siteHERE,simplybecauseInoticedtheURLforthattutorialoftenwasdown,soIrewroteit(closeto
verbatim)formyownpersonaluse.
Contents[hide]
Introduction
Requirements
AboutPHPMailer
1.PHPMailerFeatures
2.PHPMailerContributors
PreparingPHPMailerforUse
1.DownloadingandUnpacking
2.CreatingandUsingaSiteConfigurationFile
3.ThePHPMailerExtenderClass
ThePHPMailClass
1.FreakMailerClassCodeBreakdown
1.ClassControlStructure
2.ClassVariables
3.FreakMailer()Function
2.SendingEMailwithPHPMailer
1.BasicTest
1.CommonProblems
2.UsingPHPMailer'sAdditionalFeatures
1.HandlingEMailAddresses
1.AddingtheFROMAddress
2.AddingaReplyToAddress
3.AddingMultipleRecipients
4.AddingCarbonCopyCCRecipients
5.AddingBlindCarbonCopyBCCRecipients
6.AddingaReplyToAddress
7.AddingMultipleRecipients
8.RequestingaReadReceipt
2.SendingHTMLMailwithPHPandPHPMailer
1.ImportantNotesonHTMLMail
3.PHPFreaksRules!
4.PHPFreaksRules!
1.AlternateTextBodiesForHTMLMail
5.FileAttachmentsinPHPMailwithPHPMailer
6.UsingExternalSMTPServer(s)withPHPMail
1.SMTPMailProblems
7.TakingAdvantageofqmailandSendmailwithPHPMail
8.PHPMailingListExample
1.PHPMailingListCodeBreakdown
9.Summary
10.PHPMailerResources

PHPMailerisbyfartheBESTwaytoaddemailfunctionalitytoyourwebsite.
Thisisjustanarticletopointyouintherightdirectiontomasteringthisincrediblephppackage.
^Tutorials,Guides,Documentation,andHowTos
PHPMailerDocumentation(http://phpmailer.sourceforge.net/docs/)
CoupleExamplesusingPHPMailer(http://phpmailer.sourceforge.net/extending.html)
BriefPHPMailertutorialonhomesite(http://phpmailer.sourceforge.net/tutorial.html)
PHPFreaksfounder,EricRosebrock,PHPMailertutorial|Original(alternate)
http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

1/16

9/30/2016

PHPMailertutorial

^OtherPHPMailerlinks
PHPMailerHome(http://phpmailer.sourceforge.net/)
SourceforgeProjectHome(http://sourceforge.net/projects/phpmailer)
PHPMailerFAQ(http://phpmailer.sourceforge.net/faq.html)
PHPMailerMailingList(https://lists.sourceforge.net/lists/listinfo/phpmailergeneral)
PHPmail()functionreference(http://www.php.net/mail)
StandardEmailRFC822(http://rfc.askapache.com/rfc822/)
MIMEEmailRFC2046(http://rfc.askapache.com/rfc2046.txt)

^Introduction
SendingEMailthroughPHPcanbesimple,oritcanbeverycomplexdependingonwhatyouwanttodo.AstandardplaintextEMailis
whatmostdevelopersresorttobecausebuildingtheMIMEheadersforHTMLmailcanbeadifficultprocess.Thosedayshavebeenover
forquitesometimewiththeamazingPHPMailerlibrarythatisavailableforfree!Inthistutorial,Iwilldiscussindetailthefeaturesand
possibilitiesyouhavewhendealingwithPHPMailer.

^Requirements
Therequirementsofthistutorialareverylimited.YouonlyneedPHPandtheabilitytosendmail()functionoranSMTPconnection.You
shouldalsohaveabasicunderstandingofdealingwithObjectOrientedProgramming(OOP)oratleasthowtofollowtheexampleswe'll
useinthistutorial.
Don'tsweatit,thisisgoingtobeaneasytutorialforyoutofollow!

^AboutPHPMailer
PHPMailerisafullyfeaturedemailtransferclassforPHPthatIwouldputabovealloftheotherEMailhandlersthatI'veused.It's
popularityhasgrownrapidlyoverthepastyearsthatishasbeenaround.AnnouncedonthePHPMailerwebsiteonDecember7,2004,it
hasreachedover100,000downloads!Ihopeyouwillwanttoincrementthatcounterbyreadingthistutorial,andmoreimportantly,learn
howtoenableEMailfeaturesyouhaveonlydreamedof!

^PHPMailerFeatures
Atthetimethistutorialwaswritten,hereisalistoffeaturescurrentlyavailable:
CansendemailswithmultipleTOs,CCs,BCCsandREPLYTOs
RedundantSMTPservers
Multipart/alternativeemailsformailclientsthatdonotreadHTMLemail
Supportfor8bit,base64,binary,andquotedprintableencoding
Usesthesamemethods(http://phpmailer.sourceforge.net/phpdoc/default/phpmailer.html)astheverypopularAspEmailactiveserver
(COM)component
SMTPauthentication
Wordwrap
Addressresetfunctions
HTMLemail
TestedonmultipleSMTPservers:Sendmail(http://www.sendmail.org),qmail(http://www.qmail.org),Postfix(http://www.postfix.org),
Imail,Exchange,Mercury,Courier
Worksonanywin32or*nixplatform
Flexibledebugging
Custommailheaders
Multiplefs,string,andbinaryattachments(thosefromdatabase,string,etc)
Embeddedimagesupport
^PHPMailerContributors
ThefollowingcontributorstoPHPMailerare:

BrentR.Matzelle
http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

2/16

9/30/2016

PHPMailertutorial

BrentR.Matzelle
PatriceFournier
ChrisRyan
CemHurturk
TomKlingenberg
JaimeBozza
Igivethesefolksgreatrespectforwhattheyhavedonetospeedupmydevelopmenttimeonvariousprojectsinthepast,including
PHPFreaks.com!

^PreparingPHPMailerforUse
Let'sdownload,unpackandpreparePHPMailer!

^DownloadingandUnpacking
Thefirstthingyouhavetodoisofcourse,downloadPHPMailer!Youcangetitat:http://phpmailer.sourceforge.net/
(http://phpmailer.sourceforge.net/).Onceyouhavethefilesdownloaded,simplyextractthemintoadirectory.Inthistutorial,we'llassume
thatyourwebsiteissetupforthisdirectorystructure:/web/mywebsite/public_html/.Now,whatyouwanttodoiscreateacoupleof
directoriesforstructuringyourwebarea.Iusuallyputlibrariesunder'lib'andthentheirname.So,we'llextractPHPMailerinto
/web/mywebsite/public_html/lib/phpmailerandthecontentsofthisdirectorylookslikethiswiththefilesinplace:
/web/mywebsite/public_html/lib
/web/mywebsite/public_html/lib/phpmailer
/web/mywebsite/public_html/lib/phpmailer/docs
/web/mywebsite/public_html/lib/phpmailer/docs/extending.html
/web/mywebsite/public_html/lib/phpmailer/docs/faq.html
/web/mywebsite/public_html/lib/phpmailer/docs/timeoutfix.diff
/web/mywebsite/public_html/lib/phpmailer/language
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langbr.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langcz.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langde.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langen.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langes.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langfr.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langit.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langnl.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langno.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langse.php
/web/mywebsite/public_html/lib/phpmailer/language/phpmailer.langtr.php
/web/mywebsite/public_html/lib/phpmailer/phpdoc
/web/mywebsite/public_html/lib/phpmailer/phpdoc/allclassesframe.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/deprecatedlist.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/helpdoc.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/indexall.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/index.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/overviewtree.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/packages.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/phpmailer.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/serializedform.html
/web/mywebsite/public_html/lib/phpmailer/phpdoc/stylesheet.css
/web/mywebsite/public_html/lib/phpmailer/test
/web/mywebsite/public_html/lib/phpmailer/test/phpmailer_test.php
/web/mywebsite/public_html/lib/phpmailer/test/phpunit.php
/web/mywebsite/public_html/lib/phpmailer/test/rocks.png
/web/mywebsite/public_html/lib/phpmailer/ChangeLog.txt
/web/mywebsite/public_html/lib/phpmailer/class.phpmailer.php
/web/mywebsite/public_html/lib/phpmailer/class.smtp.php
/web/mywebsite/public_html/lib/phpmailer/LICENSE
/web/mywebsite/public_html/lib/phpmailer/README

Nowthatwehavethosefilesinplace,let'smoveontocreatingoursiteconfigurationfile!

^CreatingandUsingaSiteConfigurationFile
OneofthethingsIliketodowhenIbuildasiteistocreateaconfigurationfilethathandlesmiscellaneoussettingsthatImayneedover
andoveragain.So,Icreateafilecalledconfig.phpin/web/mywebsite/public_html/config.phpandIsetitupwithanarraycalled$site
withmykeysandvaluesthesettingsIuseinthesite.Inthistutorial,IwillcoverhowtodefinesomesettingswewilluseforthePHPMailer
extenderclass.Here'saviewofmyconfigurationfile:config.php

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

3/16

9/30/2016

PHPMailertutorial

<?php

//ConfigurationsettingsforMySite

//EmailSettings
$site['from_name']='MyName';//fromemailname
$site['from_email']='email@mywebsite.com';//fromemailaddress

//Justincaseweneedtorelaytoadifferentserver,
//provideanoptiontouseexternalmailserver.
$site['smtp_mode']='disabled';//enabledordisabled
$site['smtp_host']=null;
$site['smtp_port']=null;
$site['smtp_username']=null;
?>

Thepreviousexampleshouldbeveryselfexplanatory,sowe'llmoveonandcoverthosesettingslateronwhenwestarttousethem.

^ThePHPMailerExtenderClass
First,Iwanttoemphasize,youdonotneedtocreateanextenderclass,buttomakelifeeasierforus,I'mgoingtoshowyouhowto
anyways.
TheextenderclasswillbasicallycallthePHPMailer()classandthensetupthebasicvaluesforyousuchastheEmailaddressyouwant
tosendfrom,mailserversettingsandetc.Eachofthesesettingsareinheritedbytheconfig.phpbydefault,butyoumayalsooverwrite
themwhenyoucallourextenderclass.Forexample,ifyoudonotdefinethesettingsintheextenderclass,theywillbesetbydefaultand
thisinturn,allowsyoutosetupthebasicvalueswithoutactuallygoingthroughthemotionseverytime.That'sthebeautyofit!
Here'salookatourextenderclass:
MailClass.inc

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

4/16

9/30/2016

PHPMailertutorial

<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/lib/phpmailer/class.phpmailer.php');

classFreakMailerextendsPHPMailer
{
var$priority=3;
var$to_name;
var$to_email;
var$From=null;
var$FromName=null;
var$Sender=null;

functionFreakMailer()
{
global$site;

//Comesfromconfig.php$sitearray

if($site['smtp_mode']=='enabled')
{
$this>Host=$site['smtp_host'];
$this>Port=$site['smtp_port'];
if($site['smtp_username']!='')
{
$this>SMTPAuth=true;
$this>Username=$site['smtp_username'];
$this>Password=$site['smtp_password'];
}
$this>Mailer="smtp";
}
if(!$this>From)
{
$this>From=$site['from_email'];
}
if(!$this>FromName)
{
$this>FromName=$site['from_name'];
}
if(!$this>Sender)
{
$this>Sender=$site['from_email'];
}
$this>Priority=$this>priority;
}
}
?>

^ThePHPMailClass

^FreakMailerClassCodeBreakdown
TheFreakMailerclasspreviouslydisplayedisprettysimple.YouonlyneedaverybasicunderstandingofObjectOrientedProgramming
touseit,solet'sbreakitdownnow.
First,wearegoingtocalltheclass.phpmailer.phpfilefromwithinourphpmailerlibdirectoryunderthedocumentroot.Thisallowsusto
extendthePHPMailerclassbecauseitmakesthatobjectavailable.Youcouldincludethiselsewhere,butthisisagoodplacetodoso.
require_once($_SERVER['DOCUMENT_ROOT'].'/lib/phpmailer/class.phpmailer.php');

^ClassControlStructure
Next,wedefinetheclasscontrolstructureandgiveournewclassanamewhileextendingthePHPMailerclass.
classFreakMailerextendsPHPMailer
{

^ClassVariables

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

5/16

9/30/2016

PHPMailertutorial

Movingalong,wenowsetuptheinternalvariables.Mostofthesearesettonullbydefaultsothatwecandosometriggeringlateronto
determineifyouwanttooverwritethedefaultvaluesfromtheconfig.phpfile.
var$priority=3;
var$to_name;
var$to_email;
var$From=null;
var$FromName=null;
var$Sender=null;

Let'stakealookatthesevaluesnow:
$priorityThissetsthemailprioritybydefault.Values:1=High,3=Normal,5=Low
$to_nameThisisthenameofthepersonyouaresendingto
$to_emailTheEMailaddressofthepersonyouaresendingto
$FromTheEMailaddressyouwanttosendfrom
$FromNameTheNameofthesender.
Nowthatwehavethosevariablesdefined,wecandiscusstheFreakMailer()function
^FreakMailer()Function
ThisisthefunctionthatbasicallysetsupthedefaultvaluesforthePHPMailertosendEMailwith.Inotherwords,it'sthewholereason
weareusingthisclass.
First,wecallthe$sitearrayfromourconfig.phpsothatitcanbeusedwithinthisfunctionandclass.Thereareacoupleofwayswecan
dothis,wecouldpointtoitfromoutsideoftheclass,orwecanjustglobalit.Usingtheglobalcallistheeasiestmethodanditworks,so
let'sjustdothat!
functionFreakMailer()
{
global$site;//Comesfromconfig.php$sitearray

Next,westartthebulkoftheoperationshereandstartpassinginvaluestothePHPMailerclass.There'snotmuchtoexplainhere,ifthe
internalvalue($this>setting)ofthesettingisnotdefinedafteryouinstantiatetheclass,itbasicallycallsitfromtheconfig.phpandwe'll
usethatinstead.Imentionedearlierthatyoucanoverridethevaluesintheconfig.phpandthisiswherethosecheckscomeintoplay.
if($site['smtp_mode']=='enabled')
{
$this>Host=$site['smtp_host'];
$this>Port=$site['smtp_port'];
if($site['smtp_username'])
{
$this>SMTPAuth=true;
$this>Username=$site['smtp_username'];
$this>Password=$site['smtp_password'];
}
$this>Mailer="smtp";
}

if(!$this>From)
{
$this>From=$site['from_email'];
}
if(!$this>FromName)
{
$this>FromName=$site['from_name'];
}
if(!$this>Sender)
{
$this>Sender=$site['from_email'];
}
$this>Priority=$this>priority;
}

ThemostimportantthingyouneedtounderstandisthatallofthefunctionalityinthePHPMailerisstillpresentandcanbeusedeven
thoughwe'veextendedtheclass.Theonlythingwe'vedonehereiscreatedanextension(henceextends)thattakescareofthe
repetitivestuffwedon'twanttodoeverytimeweneedtosendanEMail
Nowthatwehaveagoodunderstandingoftheextenderclass,let'smovealongandstartsendingsomeEMail!

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

6/16

9/30/2016

PHPMailertutorial

SendingEMailwithPHP

^SendingEMailwithPHPMailer
We'vedoneourworkandwe'vegoteverythingreadytogotostartsendingEMailwithPHPMailer.Let'sgiveitagoandseehow
everythingworks!

^BasicTest
ThistestisveryimportanttothistutorialbecausewewillbereferringtothisbasictestcodethroughoutthetutorialwhenIshowyouhow
tousedifferentfeatureswithPHPMailer.Ifthistestdoesnotworkforyou,readthroughthetutorialagainandkeeptryinguntilitdoes
work,othewiseyouwillbelostlateron!
Ourfirstcodeexampleisgoingtobeafilelookslikethis:
<?php

//Grabourconfigsettings
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');

//GrabtheFreakMailerclass
require_once($_SERVER['DOCUMENT_ROOT'].'/lib/MailClass.inc');

//instantiatetheclass
$mailer=newFreakMailer();

//Setthesubject
$mailer>Subject='Thisisatest';

//Body
$mailer>Body='Thisisatestofmymailsystem!';

//Addanaddresstosendto.
$mailer>AddAddress('foo@host.com','EricRosebrock');

if(!$mailer>Send())
{
echo'Therewasaproblemsendingthismail!';
}
else
{
echo'Mailsent!';
}
$mailer>ClearAddresses();
$mailer>ClearAttachments();
?>

Let'sbreakdownthisfilesothatwehaveagoodunderstandingofwhatitdoes.
First,wearegoingtoincludeourconfig.phpfilewithintheDocumentRootsothatwehavethe$sitesettingsavailable.
//Grabourconfigsettings
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');

Youcoulddothisnextstepwithintheconfig.phpfile,buttomakethingseasier,Ichosenotto.
//GrabtheFreakMailerclass
require_once($_SERVER['DOCUMENT_ROOT'].'/lib/MailClass.inc');

Next,wearegoingtocallupourFreakMailerclassandwhenwedothis,we'llalsoinitializethePHPMailerclassaswellbytheextends
definitionintheFreakMailerclass.
//instantiatetheclass
$mailer=newFreakMailer();

Ok,sonowwehavePHPMailerreadytogowithallofourdefaultsettings,let'sgoaheadanddefineasubject:

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

7/16

9/30/2016

PHPMailertutorial

//Setthesubject
$mailer>Subject='Thisisatest';

Nowlet'sdefinethebodyofthemessage:
//Body
$mailer>Body='Thisisatestofmymailsystem!';

NOTE:
IfyouareusingplaintextEMail,whichisthedefault,youneedtoconvertnewlinesbyusingnorrnandyoushouldusedoublequotes
inthestringssuchas $mailer>Body .Otherwiseforsinglequotesyoucanstartyourstringandtypeitouthoweveryouwantitinyour
PHPscriptandpress <enter> foreachnewlineyouwishtomakeandwhenyouaredonewithyourstring,justenditwiththe
semicolonlikenormal.
Now,addanaddresstosendto.TheAddAddressacceptstwoinputs.ThefirstistheEmailaddresstosendtoandthesecondisthe
Nameofthepersonyouaresendingto.
//Addanaddresstosendto.
$mailer>AddAddress('foo@host.com','EricRosebrock');

Next,wesendthemessageandlookforanerror:
if(!$mailer>Send())
{
echo'Therewasaproblemsendingthismail!';
}
else
{
echo'Mailsent!';
}

Obviously,ifanerrorisdetected,youwillseeTherewasaproblemsendingthismail!,otherwiseyouwillsee:Mailsent!
Finally,wewillcleartheattatchmentlistandtheAddresslist.ThisisprimarilyforsendingMailinglists,butIdoitanywaysasa(bad?)
habit.
$mailer>ClearAddresses();
$mailer>ClearAttachments();
?>

IfyouhavejustsentyourselfanEMailwithPHPMailer,thencongratulations,you'reonyourwaytosendingEMailwithPHPtheeasy
way!
^CommonProblems
Here'salistofsomecommonproblemsyoumayhavewithsendingEMailthroughPHPMailer(theseproblemswouldprobablybethe
samewiththestandardmail()functionaswell.).
NoSMTPserverRunningonthelocalmachineYouneedsometypeofSMTPserverrunning!
ImpropersetupofthePHPscriptPleasereviewthroughthetutorialagainuntilitworks.
TheApacheWebServerisnotallowedtorelaythroughtheSMTPserveronthelocalmachine(typicalwithsomewebhosts).
Youdidnotdefinetherecipientproperly.
Alright!Ifyouhaven'thadanyproblems,let'smovealongtosendingEMailwithadditionalfeatures.Let'smoveontousingsome
additionalfeaturesinPHPMailer!
EmailwithPHPBCC,CC,ReplyTO,MultipleRecipients

^UsingPHPMailer'sAdditionalFeatures
Ifyou'reatthispointandyouhavenotreadtheentiretutorialyet,pleasegobackandread.WewillbeextendingontheBasicExample
fromthispointforward.
http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

8/16

9/30/2016

PHPMailertutorial

PHPMailerhasmanyfeaturessuchasaddingattachments,theabilitytosendamailinglist,multiplerecipients,andmuchmore.Inthis
sectionofthetutorial,we'regoingtoshowyouhowtodomostofthose.

^HandlingEMailAddresses
PHPMailersupportsmanyEMailaddressfeatures,suchasTOandFROM,multiplerecipients,CarbonCopy(BCC),ReplyToaddresses
andmore.Let'sreviewhowtoutilizethesefeatures.
Remember,wearebuildingupontheBasicExamplepresentedearlierinthistutorial,howeveryoucangenerallyapplythesemethods
intoanyPHPMailerusagebecausethesefunctionsareinthemainclass.
^AddingtheFROMAddress
Inourfileandourextenderclass,howeveryoucanoverridethatatanytime.Here'sanexample:
$mailer>FromName='YourName';
$mailer>From='You@yourdomain.com';

Thatwasprettysimple!IfyoudonotdefinetheFromNamebydefaultintheclass,itwillshowupastheEMailaddressinmostclients.
^AddingaReplyToAddress
BydefaulttheReplyToaddresswillbetheFROMaddressunlessyouspecifyotherwise.ThatissimplyEMailclientintelligence.
However,youcanhavetheEMailcomefromoneEMailaddressandanyrepliesgotoadifferentone.Here'show:
$mailer>AddReplyTo('billing@yourdomain.com','BillingDepartment');

NOTE:
YoucanhavemultipleReplyToaddresses,justduplicatethelineinthepreviouscodeexampleandchangetheEMailaddressoneach
line.
^AddingMultipleRecipients
ThismethodallowsyoutoaddmultiplerecipientstoasingleEMailaddress.Iwouldnotrecommendthisforanonymousmailinglists,or
sendingmailinglists.Seelaterinthistutorialforamailinglistexample.
ToaddmultipleRecipients,allyouhavetodoiscalltheAddAddressfunctiononceforeachEMailaddressyouwanttosendto.Here's
anexampleofthreeEMailaddresses:
NOTE:
Therearetwoargumentsinthisfunction.(RecipientEmailAddress,RecipientName).TheRecipientNameisoptionalandwillnotbe
usedifnotpresent.
$mailer>AddAddress('recipient1@domain.com','FirstPerson');
$mailer>AddAddress('recipient2@domain.com','SecondPerson');
$mailer>AddAddress('recipient3@domain.com','ThirdPerson');

NOTE:
Itisnotrecommendedtousethismethodtosendoutmailinglists!Everyrecipientthatgetsthemailwillseeeveryoneelse'sEMail
addressandyoumayhavejustviolatedanykindoftrustforyourmailinglistusers!SeelaterinthistutorialforsendingMailinglists.
^AddingCarbonCopyCCRecipients
Tocarboncopy(CC)recipientsyoucanaddthemtotheEMailgoingoutbyusingthefollowingmethods.JustliketheAddingMultiple
Recipientsexample,youcanaddmultipleCCrecipientsaswell.
http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

9/16

9/30/2016

PHPMailertutorial

$mailer>AddCC('recipient1@domain.com','FirstPerson');

//MorethanoneCC,justkeepaddingthem!
$mailer>AddCC('recipient2@domain.com','SecondPerson');
$mailer>AddCC('recipient3@domain.com','ThirdPerson');

^AddingBlindCarbonCopyBCCRecipients
The"invisible"recipientsorBCCcanbeaddedtoanEMailgoingoutbyusingthefollowingmethods.JustliketheAddingMultiple
Recipientsexample,youcanaddmultipleBCCrecipientsaswell.
$mailer>AddBCC('recipient1@domain.com','FirstPerson');

//MorethanoneBCC,justkeepaddingthem!
$mailer>AddBCC('recipient2@domain.com','SecondPerson');
$mailer>AddBCC('recipient3@domain.com','ThirdPerson');

^AddingaReplyToAddress
BydefaulttheReplyToaddresswillbetheFROMaddressunlessyouspecifyotherwise.ThatissimplyEMailclientintelligence.
However,youcanhavetheEMailcomefromoneEMailaddressandanyrepliesgotoadifferentone.Here'show:
$mailer>AddReplyTo('billing@yourdomain.com','BillingDepartment');

NOTE:
YoucanhavemultipleReplyToaddresses,justduplicatethelineinthepreviouscodeexampleandchangetheEMailaddressoneach
line.
^AddingMultipleRecipients
ThismethodallowsyoutoaddmultiplerecipientstoasingleEMailaddress.Iwouldnotrecommendthisforanonymousmailinglists,or
sendingmailinglists.Seelaterinthistutorialforamailinglistexample.
ToaddmultipleRecipients,allyouhavetodoiscalltheAddAddressfunctiononceforeachEMailaddressyouwanttosendto.Here's
anexampleofthreeEMailaddresses:
NOTE:
Therearetwoargumentsinthisfunction.(RecipientEmailAddress,RecipientName).TheRecipientNameisoptionalandwillnotbe
usedifnotpresent.
$mailer>AddAddress('recipient1@domain.com','FirstPerson');
$mailer>AddAddress('recipient2@domain.com','SecondPerson');
$mailer>AddAddress('recipient3@domain.com','ThirdPerson');

NOTE:
Itisnotrecommendedtousethismethodtosendoutmailinglists!Everyrecipientthatgetsthemailwillseeeveryoneelse'sEMail
addressandyoumayhavejustviolatedanykindoftrustforyourmailinglistusers!SeelaterinthistutorialforsendingMailinglists.
^RequestingaReadReceipt
IfyouwanttorequestaReadReceiptfromthepersonwhoreceivestheEMail,youcanusethefollowingsetting:
$mailer>ConfirmReadingTo='you@youdomain.com';

Nowthatwe'vecoveredEMailaddresses,let'smovealongtosendingthebelovedHTMLMail!

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

10/16

9/30/2016

PHPMailertutorial

HTMLMailwithPHP

^SendingHTMLMailwithPHPandPHPMailer
HTMLMailhasproventobeoneofthemorecomplicatedtaskswhensendingEMailthroughPHP.SettingtheMIMEtypesandbuilding
theboundariesofanHTMLbodyarenoteasytodoandittakessomeconsiderableresearchtogetitright.However,PHPMailerhas
madelifeeasyforusandIwillshowyouhowtodothisnow.
^ImportantNotesonHTMLMail
BeforewegotofarintosendingHTMLmail,IwantyoutounderstandthatitisimportanttoknowhowimagesandfilessuchasCSSand
etcshouldbehandled.AsimpleruleistostorethemonthewebserverandfileonthewebserverinyourHTMLthatwillbecompiled
andsentthroughtheHTMLMail.IfyougocrazyandaddabunchoffilestoanEMailandtrytocallthemwithintheEMailitself,you'rein
foronehugeheadache.AnexampleofmyHTMLbodywouldbesomethinglike:

<html>
<head>
<title>MyHTMLEmail</title>
</head>
<body>
<br/>
<h2><aid="PHP_Freaks_Rules"href="#PHP_Freaks_Rules">PHPFreaksRules!</a></h2>
<p>Weinviteyoutovisit<ahref="http://www.phpfreaks.com"title="PHPFreaks">PHPFreaks.com</a>foralovingcommunityofPHPDeve
<p>Sincerely,<br/>
PHPFreaksStaff</p>

Inthepreviousexample,ImadeeverylinkafullURLandnotashortcutrelativetomydocumentroot.Ifyoudonotdothis,thenyour
imagesandURLswillbebroken!
Movingalong,nowwearegoingtosendtheHTMLmailbysettingthebodyandatheisHTMLsettinginPHPMailer.Onceagain,this
exampleexpandsupontheBasicExampleearlierinthistutorial.

$htmlBody='<html>
<head>
<title>MyHTMLEmail</title>
</head>
<body>
<br/>
<h2><aid="PHP_Freaks_Ruless0"href="#PHP_Freaks_Ruless0">PHPFreaksRules!</a></h2>
<p>Weinviteyoutovisit<ahref="http://www.phpfreaks.com"title="PHPFreaks">PHPFreaks.com</a>foralovingcommunityofPHPDeve

<p>Sincerely,<br/>
PHPFreaksStaff</p>';

$mailer>Body($htmlBody);
$mailer>isHTML(true);

//SendtheEMail

^AlternateTextBodiesForHTMLMail
YoushouldneverrelyonHTMLonlyEMailsifyourmessageisimportant.Instead,youshoulddoyourrecipientafavorandsendatext
onlyversionoftheEMailalongwiththeHTMLbodyincasetheirEMailclientcannotdisplaytheHTMLversion.
WecanaccomplishthisbydefiningtheAltBodysettingofthePHPMailerclass.ThissettingwillbetheplaintextversionofyourEMail
andifitissetorNotEmpty,theContentTypeoftheEMailisautomaticallysettomultipart/alternative.Here'showyouwoulddothis:

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

11/16

9/30/2016

PHPMailertutorial

//setupthe$mailerclass

$htmlBody='MyHTMLBody....';
$textBody='Mytextonlybody....';

$mailer>Body($htmlBody);
$mailer>isHTML(true);
$mailer>AltBody($textBody);

//Sendthemail...

NowtwoformatsofEMailwillbesenttotherecipient.
Let'smovealongtoFileAttachmentswithPHPMailer
PHPFileAttachements

^FileAttachmentsinPHPMailwithPHPMailer
Sendingfileattachmentsisreallyeasytodo.Yousimplyaddthemtotheattachmentjustlikeyouwouldanaddress,cc,bccorreplyto,
exceptusingtheproperfunction.Seetheexamplebelow:
//Setupmailclass,recipientsandbody
$mailer>AddAttachment('/web/mywebsite/public_html/file.zip','file.zip');

TheAddAttachmentfunctionhasfourarguments:
AddAttachment(PATH_TO_FILE,FILENAME,ENCODING,HEADER_TYPE)
ThePATH_TO_FILEisnaturallythefullpathoftheheaderyouwanttosend.Application/octetstreamisdefault.
Thatwasprettyeasy!Let'smovealongtousingSMTPserversandutilizingdiferenttypesoflocalEmailSMTPservers.
SMTPServerswithPHPMail

^UsingExternalSMTPServer(s)withPHPMail
First,let'sdiscussusingexternalSMTPserversinsteadoflocalhost.Inthistutorial,wesetupaconfig.phpfile.Insidethisfile,wehavea
fewoptionsforSMTPservers.IfyouwanttosimplyenableonemoremoreSMTPservers,youcandosothroughthisconfigurationfileby
setting$site['smtp_enabled']='enabled'
Inthe$site['smtp_host']settingyoucanhavealistofSMTPserverstosendthroughdelimitedbyasemicolon:
FrommyunderstandingofthisSMTPsetting,PHPMailerwillsendEMailthroughthemainhostfirstandifitcannotconnect,itwillgoto
thenextoneinthelist.
NOTE:
Remember,youcanenableSMTPauthenticationandchangetheSMTPportviayourconfig.phpfilewiththebasicsettingsthatwe
created.
OneimportantthingtonoteaboutsendingthroughSMTPisthatinsteadofusingthestandardSend()function,youwilluseSMTPSend()
Example:

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

12/16

9/30/2016

PHPMailertutorial

//Classandmailbodysetuphere....
//SeebasicExample.

//NonSMTPMode:
//$mailer>Send();

//SMTPMode:
$mailer>SmtpSend();

^SMTPMailProblems
TherearemanythingsthatcangowrongwithsendingmailthroughSMTPandmostoftheproblemscomefrompermissionissues.
DoesyourHosthavepermissiontorelaythroughtheSMTPHost?
DoesyourhostrequirePOPbeforeSMTP?
DoesyourHostrequireSMTPauthentication?
AreyourSMTPsettingscorrectfortheremotehostusername/password?
NOTE:
Unfortunately,IdonotbelievePHPMailersupportsPOPbeforeSMTP.Ifthisisaproblemforyou,youshouldcontactyoursystem
administratorandrequestaRELAYHOSTbesetupforyourwebserver'sIPaddress.

^TakingAdvantageofqmailandSendmailwithPHPMail
IfyouwanttobypassthePHPMailserverandthenPHPMailerwillexecutethatBinarywhichcouldpossiblyspeedthingsupquiteabit.
qmailExample:
//SetupMailclassandfeatures
$mailer>IsQmail();
$mailer>Send();

SendmailExample:
//SetupMailclassandfeatures
$mailer>IsSendmail();
$mailer>Send();

Thatwasprettyeasy!Let'smovealongtocreatingasimpleMailinglistwithPHPMailer!
PHPMailingListExample

^PHPMailingListExample
NowthatyouhaveagoodunderstandingofthePHPMailerandhowitworks,let'sdiscusssomeMailingListfeatures.Afew
considerationsyoumayhaveaboutsendingmailinglistsarecustomizablesubjects,bodiesandpossiblyevencontent.Moreimportantly,
istheabilitytohidetheEMailaddressesofeveryoneelseonthelistfromeachother.
ThisexampleassumesthatyoualreadyhavesomesortofdatabasesetupformailinglistusersandyouknowhowtoconnecttoMySQL
andquerydata.Ifyoudon'tknowhowtodothat,thenthere'ssometutorialsonthissitethatcanhelpyougettothispoint.Fornow,we'll
assumethatwehavesomethingofthefollowingtablestructure:
FirstName
LastName
EmailAddress
MailType(text/html)
Let'sassumethatyouhave50usersinyourdatabaseandyouwanttoEMailthemallacustomizableEMail.Thefollowingcodewill
accomplishthisforyou:

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

13/16

9/30/2016

PHPMailertutorial

<?php
//Grabourconfigsettings
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');

//GrabtheFreakMailerclass
require_once($_SERVER['DOCUMENT_ROOT'].'/lib/MailClass.inc');

//Setupbody
$textBody="Dear{MEMBER_NAME},nnCheckoutPHPFreaks:http://www.phpfreaks.comnnSincerely,nAdmin";
$htmlBody="Dear{MEMBER_NAME},<br/><br/>CheckoutPHPFreaks:http://www.phpfreaks.com<br/><br/>Sincerely,<br/>Admin";

//instantiatetheclass
$mailer=newFreakMailer();

//Gettheuser'sEmail
$sql=mysql_query("SELECTFirstName,LastName,EmailAddress,MailTypeFROMusersWHERE1");

while($row=mysql_fetch_object($sql))
{
//Sendtheemailsinthisloop.
$member_name=$row>FirstName;
if(!empty($row>LastName))
{
$member_name.=''.$row>LastName;
}

if($row>MailType=='html')
{
$mailer>Body=str_replace('{MEMBER_NAME}',$member_name,$htmlBody);
$mailer>IsHTML(true);
$mailer>AltBody=str_replace('{MEMBER_NAME}',$member_name,$textBody);
}
else
{
$mailer>Body=str_replace('{MEMBER_NAME}',$member_name,$textBody);
$mailer>isHTML(false);
}
$mailer>Send();
$mailer>ClearAddresses();
$mailer>ClearAttachments();
$mailer>IsHTML(false);
echo"Mailsentto:$member_name<br/>";
}

?>

^PHPMailingListCodeBreakdown
Let'sbreakthiscodedownforfurtherunderstanding.
Thefirstportionisjustlikeourbasicexampleearlierinthistutorial.Itincludesthescriptsweneedtoinstantiatetheclass.
<?php
//Grabourconfigsettings
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');

//GrabtheFreakMailerclass
require_once($_SERVER['DOCUMENT_ROOT'].'/lib/MailClass.inc');

Next,wewillgoaheadandfile_get_contents()functiontoreadtheseintothescript,buttokeepitsimplehere,wejustuseasmallstring
instead.
Noticethe{MEMBER_NAME}placeholdersthatIhaveputintotheseexamples.Laterwhenweloopthroughtheusers,we'll
str_replace()thiswiththeiractualinformation.
//Setupbody
$textBody="Dear{MEMBER_NAME},nnCheckoutPHPFreaks:http://www.phpfreaks.comnnSincerely,nAdmin";
$htmlBody="Dear{MEMBER_NAME},<br/><br/>CheckoutPHPFreaks:http://www.phpfreaks.com<br/><br/>Sincerely,<br/>Admin";

Next,wewillgoaheadandgetourMailclassready:

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

14/16

9/30/2016

PHPMailertutorial

//instantiatetheclass
$mailer=newFreakMailer();

Now,thisiswhereyouwillhavetocreateyourowntablesandgetyourowndata.Thisisasimplemysql_fetch_object()
//Gettheuser'sEmail
$sql=mysql_query("SELECTFirstName,LastName,EmailAddress,MailTypeFROMusersWHERE1");

while($row=mysql_fetch_object($sql))
{

Now,thisiswheretheheartoftheEMailsendingoccurs.Thisisextremelyimportantforyoutopayattentionhere.Thefirstportionofthe
codewillbasicallycreatethe$member_namestringwhichwillcontainthisspecificuser'sinformationforthisportionoftheloop.
$member_name=$row>FirstName;
if(!empty($row>LastName))
{
$member_name.=''.$row>LastName;
}

OurMailpreferences.Iftheuser'sMailTypeissetto'html'inthedatabase,thenwe'llsendthemanHTMLEMailwithaplaintext
alternativebody.Otherwise(else)we'llsendthemjustaplaintextEMail.
if($row>MailType=='html')
{
$mailer>Body=str_replace('{MEMBER_NAME}',$member_name,$htmlBody);
$mailer>IsHTML(true);
$mailer>AltBody=str_replace('{MEMBER_NAME}',$member_name,$textBody);
}
else
{
$mailer>Body=str_replace('{MEMBER_NAME}',$member_name,$textBody);
$mailer>isHTML(false);
}

Pleaseanalyzethecodeaboveuntilyouunderstandit.Thisinformationwaspreviouslydiscussedinthistutorialandyoushouldbe
familiarwithhowtosendPlainTextandHTMLEMails.
Finally,wesendouttheEMailandthencleartheaddressesfromthe$mailerobjectaswellasanyattachmentsyoumayhave.
$mailer>Send();
$mailer>ClearAddresses();
$mailer>ClearAttachments();
$mailer>IsHTML(false);
echo"Mailsentto:$member_name<br/>";

NOTE:
PleasemakesurethatyouusetheClearAddress()andClearAttachments()functionsotherwisetheusersintheMailinglistwillalwaysbe
appendedtothelist.Trustmeonthisone!

^Summary
ThistutorialshouldhavegivenyouagoodpushintherightdirectiontomakinglifeeasierwithsendingEMailthroughPHP.Thanksto
theexcellentPHPMailerclassandthedevelopersofit,wecannowsendEMailwithoutmemorizingorconstantlylookingupheaders
whenweneedtosendmorecomplexeEMails.
IfyousetthisMailportionsandmoveontomorecomplicatingthingswithoutwastingyourtime.

^PHPMailerResources
IhopeyoutakethePHPMailerFAQ.ItisimportanttounderstandthisclassandreadwhattheDevelopershavesaidaboutit.Inaddition,
thereisanothergreattutorial(http://phpmailer.sourceforge.net/tutorial.html)andsomeexamples
(http://phpmailer.sourceforge.net/extending.html)forPHPMailerontheirwebsite(http://phpmailer.sourceforge.net).Goodluck!phpfreak

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

15/16

9/30/2016

PHPMailertutorial

^Tags
14Dec,200626Apr,2013
SpeedUpSiteswithhtaccessCachingLFTtraceroutetool

^CommentsWelcome
[hide]
It'sverysimpleyoureadtheprotocolandwritethecode.BillJoy
RSS(http://feedvalidator.org/check.cgi?url=http://www.askapache.com/feed/)|XHTML1.1(http://validator.w3.org/check/referer?
ss=1outline=1sp=1debug)|CSS2.1(http://jigsaw.w3.org/cssvalidator/check/referer?warning=0)
Exceptwhereotherwisenoted,contentonthissiteislicensedunderaCreativeCommonsAttribution3.0License
(http://creativecommons.org/licenses/by/3.0/),justcreditwithalink.
ThissiteisnotsupportedorendorsedbyTheApacheSoftwareFoundation(ASF).AllsoftwareanddocumentationproducedbyTheASF
islicensed."Apache"isatrademarkofTheASF.NCSAHTTPd(http://hoohoo.ncsa.illinois.edu/).
UNIXisaregisteredTrademarkofTheOpenGroup(http://www.opengroup.org/).POSIXisaregisteredTrademarkofTheIEEE
(http://standards.ieee.org/).
+Askapache(https://plus.google.com/+Askapache)|htaccess.io(http://htaccess.io/)
SiteMap|ContactWebmaster|LicenseandDisclaimer|TermsofService|@Htaccess
Main(http://www.quantcast.com/p5e44cjdXWaqOA)(http://www.alexa.com/data/details/main/www.askapache.com)

http://www.askapache.com/php/phpfreaksericrosebrocksphpmailertutorial.html

16/16

Вам также может понравиться