0% found this document useful (0 votes)
310 views

PHPMailer Tutorial

This tutorial provides an overview of PHPMailer, an open source library for sending email from PHP. It discusses PHPMailer features, how to download and prepare it for use, creating a configuration file, and the basics of sending email with PHPMailer including addressing, attachments, and more.

Uploaded by

Boz Lee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
310 views

PHPMailer Tutorial

This tutorial provides an overview of PHPMailer, an open source library for sending email from PHP. It discusses PHPMailer features, how to download and prepare it for use, creating a configuration file, and the basics of sending email with PHPMailer including addressing, attachments, and more.

Uploaded by

Boz Lee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 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 protected]';//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('[email protected]','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('[email protected]','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='[email protected]';

Thatwasprettysimple!IfyoudonotdefinetheFromNamebydefaultintheclass,itwillshowupastheEMailaddressinmostclients.
^AddingaReplyToAddress
BydefaulttheReplyToaddresswillbetheFROMaddressunlessyouspecifyotherwise.ThatissimplyEMailclientintelligence.
However,youcanhavetheEMailcomefromoneEMailaddressandanyrepliesgotoadifferentone.Here'show:
$mailer>AddReplyTo('[email protected]','BillingDepartment');

NOTE:
YoucanhavemultipleReplyToaddresses,justduplicatethelineinthepreviouscodeexampleandchangetheEMailaddressoneach
line.
^AddingMultipleRecipients
ThismethodallowsyoutoaddmultiplerecipientstoasingleEMailaddress.Iwouldnotrecommendthisforanonymousmailinglists,or
sendingmailinglists.Seelaterinthistutorialforamailinglistexample.
ToaddmultipleRecipients,allyouhavetodoiscalltheAddAddressfunctiononceforeachEMailaddressyouwanttosendto.Here's
anexampleofthreeEMailaddresses:
NOTE:
Therearetwoargumentsinthisfunction.(RecipientEmailAddress,RecipientName).TheRecipientNameisoptionalandwillnotbe
usedifnotpresent.
$mailer>AddAddress('[email protected]','FirstPerson');
$mailer>AddAddress('[email protected]','SecondPerson');
$mailer>AddAddress('[email protected]','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('[email protected]','FirstPerson');

//MorethanoneCC,justkeepaddingthem!
$mailer>AddCC('[email protected]','SecondPerson');
$mailer>AddCC('[email protected]','ThirdPerson');

^AddingBlindCarbonCopyBCCRecipients
The"invisible"recipientsorBCCcanbeaddedtoanEMailgoingoutbyusingthefollowingmethods.JustliketheAddingMultiple
Recipientsexample,youcanaddmultipleBCCrecipientsaswell.
$mailer>AddBCC('[email protected]','FirstPerson');

//MorethanoneBCC,justkeepaddingthem!
$mailer>AddBCC('[email protected]','SecondPerson');
$mailer>AddBCC('[email protected]','ThirdPerson');

^AddingaReplyToAddress
BydefaulttheReplyToaddresswillbetheFROMaddressunlessyouspecifyotherwise.ThatissimplyEMailclientintelligence.
However,youcanhavetheEMailcomefromoneEMailaddressandanyrepliesgotoadifferentone.Here'show:
$mailer>AddReplyTo('[email protected]','BillingDepartment');

NOTE:
YoucanhavemultipleReplyToaddresses,justduplicatethelineinthepreviouscodeexampleandchangetheEMailaddressoneach
line.
^AddingMultipleRecipients
ThismethodallowsyoutoaddmultiplerecipientstoasingleEMailaddress.Iwouldnotrecommendthisforanonymousmailinglists,or
sendingmailinglists.Seelaterinthistutorialforamailinglistexample.
ToaddmultipleRecipients,allyouhavetodoiscalltheAddAddressfunctiononceforeachEMailaddressyouwanttosendto.Here's
anexampleofthreeEMailaddresses:
NOTE:
Therearetwoargumentsinthisfunction.(RecipientEmailAddress,RecipientName).TheRecipientNameisoptionalandwillnotbe
usedifnotpresent.
$mailer>AddAddress('[email protected]','FirstPerson');
$mailer>AddAddress('[email protected]','SecondPerson');
$mailer>AddAddress('[email protected]','ThirdPerson');

NOTE:
Itisnotrecommendedtousethismethodtosendoutmailinglists!Everyrecipientthatgetsthemailwillseeeveryoneelse'sEMail
addressandyoumayhavejustviolatedanykindoftrustforyourmailinglistusers!SeelaterinthistutorialforsendingMailinglists.
^RequestingaReadReceipt
IfyouwanttorequestaReadReceiptfromthepersonwhoreceivestheEMail,youcanusethefollowingsetting:
$mailer>ConfirmReadingTo='[email protected]';

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

You might also like