Professional Documents
Culture Documents
UbuntuEmailServer
Articles
Projects
Downloads
tutorialsetc.
websites
scripts&stuff.
IamadanishprogrammerlivinginBangkok.
Readmoreaboutme@rasmus.rummel.dk.
Dogood
Suka
Tweet
UbuntuEmailServer
10Feb2012.ThistutorialisastepbystephowtomakeUbuntuintoapowerfulemailserverusingPostfix,Dovecot,MySQLandSquirrelmail.
Tomakeiteasy,Ihavemadeanemailserverinstallationscriptwhichallowsyoutochooseoneofthe3followingscenarios:
Youwanttoinstallastandalonefullfledgedemailserverinstallationscriptoption1.
YouwanttoenhanceyourLAMPstackwithanemailserverinstallationscriptoption2.
Youwanttounderstandhowtoinstallanemailserverinstallationscriptoption3willholdyourhandwhilefollowingthistutorial.
Installmailserverstepbystep:
1. Install&configurebasicmailserver(test)
2. Configurevirtualdomains(test)
3. Installspamcontrolunderconstruction
4. ConfigureSASL(test)
5. ConfigureTLS(test)
6. InstallSquirrelmail(test)
Appendixes:
Appendix:AccessSquirrelmailonmultiplecustomurls
Appendix:Management&DebuggingCommands
Appendix:BasicConceptsifyouarenewtoemailconcepts,skimthisfirst
Appendix:Relevantlinks
Appendix:Squirrelmailinthai
Appendix:Commonerrors&solutions
Comments
Toomuchtalkingalready
Installbasicmailcomponents
AnEmailserverisaboutlettingaMailUserAgent(MUA)alsocalledanemailclient,eg.OutlookExpress
orThunderbird,sendingandreceivingemailmessages.Aminimalworkingemailserverconsistsof2components:
AMailTransferAgent(MTA):wewillusePostfix:basicallyresponsibleforlettingaMUAsendanemailmessage.
AMailDeliveryAgent(MDA):wewilluseDovecot:basicallyresponsibleforlettingaMUAreceiveanemailmessage.
BasicmailcomponentsinstallPostfix(alternativelyexecuteemailserverinstallationscriptstep3>1)
1. Logontoyourserverasroot(orlogonasyournormaluserandthenswitchusertoroot:shell> suroot).
2. shell> aptgetupdate:alwaysstartwithupdatingpackageinformation.
3. InstallPostfix:
1. shell> aptgetyinstallpostfixpostfixdoc:
postfix:MTAmailserver
postfixdoc:documentationforPostfix,notnecessarybutnicetohave.
Installingthepostfixpackagewillpromptyoufor:
1.
generaltype:youshouldchooseinternetsite.
2.
Systemmailname:youinternetdomainnameusedtoqualifyyouremails,eg.ifyouwanttoreceive
rasmus@webmodelling.com,thenthevalueshouldbewebmodelling.com
4. ConfigurePostfix:(postconfeisaconvenientwaytosetconfigurationpropertiesin/etc/postfix/main.cf)
1. shell> postconfe'myhostname=host.example.tld':changehost.example.tldtoyourownserversFQDN(FullyQualifiedDomainName),eg.
web1.webmodelling.comormaybejustwebmodelling.com.
2. shell> postconfe'mydomain=example.tld':standardistouseyourserversinternetdomainwithoutthehostname.IfyourFQDNis
host.example.tld,thenyoushouldonlyhaveexample.tldhere.
3. shell> postconfe'mydestination=$mydomain,localhost,localhost.localdomain':listofdomainsthatPostfixshoulddeliverlocally.If
mydestinationissettowebmodelling.com,thenallemailmessagesxxx@webmodelling.comwillbedeliveredlocally(andallother
emailmessageswillbeforwardedtoanotherMTA).Herethevalueissetto$mydomainandlocalhostetc.
4. shell> postconfe'mynetworks=127.0.0.0/8[::ffff:127.0.0.0]/104[::1]/128':listoftrustednetworksfromwhichSMTPclients(MUAs&other
MTAs)havemorepriviledges,typicalltrustedSMTPclientsareallowedtorelayemailmessageswhilenontrustedarenot.
5. shell> postconfe'inet_interfaces=all':whatinterfacestoreceiveemailon,eitherspecifycommaseperatedIPaddressesorspecifyall.
6. shell> postconfe'home_mailbox=Maildir/':setmailboxformattoMaildir(eachemailmessageinitsownfile).
7. shell> postconfe'smtpd_sasl_auth_enable=no':whiledocumentationstatesthisvaluesisdefaultsettono,actuallyitseemsdefaulttobe
yesandsincewedonotwanttoenablesaslauthyet,wesetitexplicitlytonohere.
8. shell> /etc/init.d/postfixrestart:restartPostfixtoapplythechangedconfiguration.
BasicmailcomponentsinstallDovecot(alternativelyexecuteemailserverinstallationscriptstep3>2)
1. Logontoyourserverasroot(orlogonasyournormaluserandthenswitchusertoroot:shell> suroot).
2. InstallDovecot:
1. shell> aptgetyinstalldovecotcommondovecotimapddovecotpop3ddovecotpostfix
dovecotcommon:MDA(MailDeliveryAgent).Isresponsibleforstoringfinalreceivedemailmessages(typicallyonharddrive).
Alsodovecotpop3danddovecotimapdependsonthispackage.
dovecotimapd:AllowsMUAs(MailUserAgents)todownloademailmessagesusingtheIMAPprotocol.
dovecotpop3d:AllowsMUAs(MailUserAgents)todownloademailmessagesusingthePOP3protocol.
dovecotpostfix:MailstackdeliveryintegrationIhavenottestedit,butIguessthepackagewilltrytosetupPostfixtouse
DovecotLDAaswellasinstallSieve.
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
1/18
4/8/2015
UbuntuEmailServer
DovecotLDAaswellasinstallSieve.
3. ConfigureDovecot:
Dovecotmainconfigurationfile/etc/dovecot/dovecot.confnowincludeslotsofseparateconfigurationfilesunder/etc/dovecot/conf.d/for
defaultconfigurationsettings.Themostimportantoftheseis/etc/dovecot/conf.d/01mailstackdelivery.conf.
1. shell> dovecotn|headn1:displayspathtoDovecotmainconfigfileshouldbe /etc/dovecot/dovecot.conf.
2. shell> nano/etc/dovecot/dovecot.conf:loadDovecotmainconfigurationfileinthenanoeditorandbesureitcontainsthefollowinglines
(exceptthosestrikedthrough).
protocols=pop3imap:notnecessarytoset,alreadysetinconf.d/01mailstackdelivery.conf.
mail_location=maildir:~/Maildir/:notnecessarytoset,alreadysetinconf.d/01mailstackdelivery.conf.
pop3_client_workarounds=outlooknonulsoenseoh :notnecessarytoset,alreadysetinconf.d/01mailstackdelivery.conf.
Workaroundsforemailclientbugs.Outlook&OutlookExpresshangsifmailcontainsNULcharacters.outlooknonulsreplaces
NULswith0x80.OutlookExpressandNetscapeMailbreaksifendofheaderslineismissing.oenseohsendsendofheadersline
ifit'smissing.
!includeconf.d/*.conf:loadallconfigurationfiles.
pop3_uidl_format=%08Xu%08Xv:formatofPOP3uniquemailidentifier.
log_timestamp="%Y%m%d%H:%M:%S":prefixforeachlinewrittentologfile.
imap_client_workarounds=delaynewmailoutlookidlenetscapeeoh :thisisalsosetinconf.d/01mailstackdelivery.conf,
howeverthevalueisnotcorrect,soweoverwriteithere.Workaroundsforemailclientbugs.
namespace{ :namespaceisnotstrictlyrequiredasadefaultnamespacewillbecreatedifyoudon'tcreateityourself.
type=private:thisnamespacecontainsonlytheusersownmailboxes.(therearealsosharedandpublictypes).
separator=.:charforseparatingchildfolders,eg.work.designorwork.programming.
prefix=INBOX.
inbox=yes:thisnamespacecontainstheinbox(thereareonlyoneinbox).
}
3. shell> /etc/init.d/dovecotstop&&sleep5&&/etc/init.d/dovecotstart:restarttheDovecotservertoenabletheconfigurationchanges(wait5
secondsbetweenstopandstartquatheansilchildprocessbug).
BasicmailserverTestitworks
Logontoyourserverasroot(orlogonasyournormaluserandthenswitchusertoroot:shell> suroot).
Testthatserversareontherightports:
1. shell> nmaplocalhost:showsallportsonwhichserversarelisteningusingwhichprotocolyoushouldhaveatleast:
25/tcpopensmtp
110/tcpopenpop3
143/tcpopenimap
993/tcpopenimaps
995/tcpopenpop3s
TestthatPostfixworks:(manuallysendinganemailthroughPostfix)
1. shell> telnetlocalhost25:probetheserveronport25(Postfix)tobesurePostfixislistening.
1. Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.
220Your.Domain.NameESMTPPostfix(Ubuntu)
2.
3.
4.
5.
6.
helolocalhost:(moreinfowith ehlolocalhost)
250your.domain.name
mailfrom:root@localhost
2502.1.0Ok
rcptto:rasmus@localhost:useavaliduserdifferentfromroot(theuserneedtohaveapassword,otherwisetheusercannotretrieve
mail)
7.
8.
9.
10.
11.
12.
13.
14.
15.
2502.1.5Ok
data:beginthedatasection.
354Enddatawith<CR><LF>.<CR><LF>
Subject:myfirstsubject
Myfirstbody
.:adotonanewlinefollowedbyEnterwillendthedatasection.
2502.0.0Ok:queuedas31410102286
quit:
2212.0.0Bye
Connectionclosedbyforeignhost.
2. shell> lsl/home/rasmus/Maildir/new:listtheemailmessagetoseethatithavebeenlocallydelivered(besuretochangerasmustoyour
ownuser)
3. shell> cat/home/rasmus/Maildir/new/*:youcanalsoreadtheemailmessage.
4. shell> telnetyour.server.domain25:shouldgivethesameresultas telnetlocalhost25andconfirmsthatyouhaveindeedusedthecorrect
FQDNforPostfixmyhostnameabove.
TestthatDovecotworks:(retrievingtheemailusingDovecotpop3justsentthroughPostfixabove)
1. shell> telnetlocalhostpop3
1. Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.
+OKDovecotready.
2.
3.
4.
5.
6.
7.
userrasmus:theuser
+OK
passPASSWORD:insertthepasswordfortherasmususer.
+OKLoggedin.
list
+OK1messages:
1420
.
8. retr1
9. +OK420octets
ReturnPath:<root@localhost>
XOriginalTo:rasmus@localhost
DeliveredTo:rasmus@localhost
Received:fromlocalhost(localhost[127.0.0.1])
byyour.server.domain(Postfix)withSMTPid31410102286
for<rasmus@localhost>Wed,7Dec201119:58:25+0700(ICT)
Subject:myfirstsubject
MessageId:<20111207125833.31410102286@your.server.domain>
Date:Wed,7Dec201119:58:25+0700(ICT)
From:root@localhost
Myfirstbody
.
10. quit
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
2/18
4/8/2015
UbuntuEmailServer
10. quit
2. shell> lsl/home/rasmus/Maildir/new:afterretrievingtheemailusingpop3,theemailmessagehavebeenremovedfromthenewfolder...
3. shell> lsl/home/rasmus/Maildir/cur:...tothecurfolder.
Ifyoupassedthetests,younowhaveabasicemailserverthatactuallyworks.
ConfigurePostfixforvirtualdomainsusingMySQL(alternativelyexecuteemailserverinstallationscriptstep3>3)
MostemailserversneedtobefinalMTArecipientformultiplevirtualdomainsandmanymanyemailaddresses.These2tasksarebyfarmost
easilyhandledusingaMySQLdatabase.
WhilewestorevirtualdomainsandvirtualemailaddressesinaMySQLdatabase,westillstoretheactualemailmessagesonstandardstorage
(harddrive).Alsowewilluseonesystemaccount,vmail,inwhichhomefolderwewillwriteafolder,email_box,foreachemailaddress.
Ifwedidnotusevirtualdomainsandthereforevirtualmailboxes,defaultistostoreemailmessagesinthesystemusershomedirectory.However,
sinceourusersarevirtual,weinsteadhaveavirtual_mailbox_base,wewilluse/home/vmail,andthensubfoldersforeach
virtual_mailbox_domain.
1. shell> aptgetyinstallmysqlclientmysqlserverpostfixmysqldovecotmysql:ifyoualreadyhaveMySQLinstalled,thenjustinstallthepostfixmysql
&dovecotmysqlpackages.
mysqlserver:theactualmysqlserverthatenablesyoutocreatedatabases.
mysqlclient:thisisthemysqlCLIthatallowsyoutoaccessandmanagemysqlserveranddatabasesusingthecommandline(aGUI
alternativeisphpMyAdmin).
postfixmysql:addsMySQLmapssupporttoPostfix.MakesitpossibletoconfigurePostfixtouseMySQLtostoreuseraccountsand
relateddata.
dovecotmysql:addsMySQLdriversupporttoDovecot.
Installingthemysqlserverpackagewillpromptyoufor:
1.
rootuserpassword:createapasswordforMySQLrootuser(notUbunturootuser).
2.
confirmrootuserpassword.
2. CreatethePostfixMySQLdatabase:
1. shell> mysqlurootpRootPassword:usemysqlclienttologontoMySQL.BesuretochangePasswordtothecorrectpassword(noticethere
isnospacebetweenpandPassword).
2. mysql> CREATEDATABASEPostfix;:
3. mysql> GRANTSELECT,INSERT,UPDATE,DELETEONPostfix.*TO'mail_admin'@'localhost'IDENTIFIEDBY'MailAdminPassword';:Youmakeupthe
MailAdminPasswordyourself.
4. mysql> GRANTSELECT,INSERT,UPDATE,DELETEONPostfix.*TO'mail_admin'@'localhost.localdomain'IDENTIFIEDBY'MailAdminPassword';:
5. mysql> USEPostfix;:
6. mysql> CREATETABLEdomains(domainvarchar(50)NOTNULL,PRIMARYKEY(domain));:
7. mysql> CREATETABLEforwardings(sourcevarchar(80)NOTNULL,destinationTEXTNOTNULL,PRIMARYKEY(source));:
8. mysql> CREATETABLEusers(emailvarchar(80)NOTNULL,passwordvarchar(20)NOTNULL,PRIMARYKEY(email));:
9. mysql> CREATETABLEtransport(domainvarchar(128)NOTNULLdefault'',transportvarchar(128)NOTNULLdefault'',UNIQUEKEYdomain(domain));:
10. mysql> quit:Postfixdatabaseschemaisfinished.
11. shell> sedie"s/^[\t#]*bindaddress.*$/bindaddress=127.0.0.1/"/etc/mysql/my.cnf:uncommenttheMySQLlocalbindaddresstogetMySQL
tobindtolocalhostsothatthePostfixmail_adminusercanconnect(ifyouneedtouseanotherIP,youwillneed1)tocreatea
mail_adminuseronthatIPinsteadoflocalhostand2)changethehostvalueofthemysqlmapfilesbelow).
12. shell> servicemysqlrestart:reloadMySQLconfigurationfile.
3. WritePostfix/MySQLmapfiles:4filesthatdefineshowPostfixmapsdomains,mailboxes,forwardingsandaccountstotablesintheabove
PostfixMySQLdatabase:
(Anaturalplacetosavethe4filesisin/etc/postfix.Alsonotethatthefilesdifferonlywithrespecttothequeryline)
1. shell> cd/etc/postfix:changelocationtotheplacetherethe4filesshouldbecreated.
2. shell> nanomysqlvirtual_domains.cf:createafilecalledmysqlvirtual_domains.cf
user=mail_admin
password=MailAdminPassword:besuretosubstituteMailAdminPasswordwiththepasswordyoucreatedfor
mail_admin@localhostabove.
dbname="postfix"
query=SELECTdomainASvirtualFROMdomainsWHEREdomain='%s'
hosts=127.0.0.1
3. shell> nanomysqlvirtual_mailboxes.cf:createafilecalledmysqlvirtual_mailboxes.cf
user=mail_admin
password=MailAdminPassword
dbname="postfix"
query=SELECTCONCAT(SUBSTRING_INDEX(email,'@',1),'/',SUBSTRING_INDEX(email,'@',1),'/')FROMusersWHERE
email='%s'
hosts=127.0.0.1
4. shell> nanomysqlvirtual_forwardings.cf:createafilecalledmysqlvirtual_forwardings.cf
user=mail_admin
password=MailAdminPassword
dbname="postfix"
query=SELECTdestinationFROMforwardingsWHEREsource='%s'
hosts=127.0.0.1
5. shell> nanomysqlvirtual_email2email.cf:createafilecalledmysqlvirtual_email2email.cf
user=mail_admin
password=MailAdminPassword
dbname="postfix"
query=SELECTemailFROMusersWHEREemail='%s'
hosts=127.0.0.1
6. shell> chmodo=/etc/postfix/mysqlvirtual_*.cf:changeaccessfortheabove4mappingfiles.
7. shell> chgrppostfix/etc/postfix/mysqlvirtual_*.cfchangethegroupfortheabove4mappingfiles.
4. Createthesystemgroupanduserthatvirtualdomainemailmessagefilesbelongsto:
1. shell> groupaddg5000vmail:createagroupcalledvmailwithGroupID=5000(g)
2. shell> useraddgvmailu5000s/sbin/nologinvmaild/home/vmailm:createausercalledvmailwithUserID=5000(u)belongingtothe
vmailgroup(g)withoutashelllogin(s)andwithhomedirectory/home/vmail(d).If/home/vmaildoesnotexist,thenmakeit(m).
3. shell> chmod770/home/vmail:giveownerandgroupfullaccessandothersnoaccess.
5. ConfigurePostfixvirtualdomains:(usingtheabovefilestomapdomainslistandemailaccountslisttoMySQL):
1. shell> postconfe'virtual_alias_domains=':
Avirtualaliasdomainisadomainonwhichemailaccountsaremappedtosystemusers,eg.ifexample.tldisspecifiedasavirtual
aliasdomainthencontact@example.tldcouldbemappedtoasystemusercalledrasmustherebygivingthatsystemuseraccessto
havingemailaccountsonmultipledomains.However,Ithinkthissettingisdeprecatedespeciallyitdoesnotallowanyonetohavean
emailaddresswithoutalsohavingasystemaccount,aproblemsolvedwithvirtual_mailbox_domains.NEVERlistavirtualaliasdomain
asamydestinationdomain.
2. shell> postconfe'virtual_alias_maps=proxy:mysql:/etc/postfix/mysqlvirtual_forwardings.cf,mysql:/etc/postfix/mysqlvirtual_email2email.cf':
listofdomainaliasesandemailaddressaliases.Eg.example.tldcouldbeanaliasforwebmodelling.com,sorasmus@example.tld
wouldactuallyberewrittentorasmus@webmodelling.com.
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
3/18
4/8/2015
UbuntuEmailServer
3.
4.
5.
6.
7.
8.
wouldactuallyberewrittentorasmus@webmodelling.com.
shell> postconfe'virtual_mailbox_domains=proxy:mysql:/etc/postfix/mysqlvirtual_domains.cf':
Sameasmydestination,thatis:allthedomainsforwhichPostfixshoulddeliverlocallyandinthe/etc/vmailfoldertherewillbe
createdasubfolderforeachofthesedomainstosaveemailmessagesreceived,eg.anemailmessagetorasmus@webmodelling.com
willbesavedinthewebmodelling.commailboxfolder(itisthevirtualdeliveryagentthatdeliversdomainsinvirtual_mailbox_domains,
whileIthinkitisthelocaldeliveryagentthatdeliversdomainsinmydestination).
ifnotusingMySQL,wecouldwritethisinstead:postconfe'virtual_mailbox_domains=webmodelling.comanother.domain
athird.domain'orwecouldcreateafileandthenreferencethefilelike:postconfe'virtual_mailbox_domains=
/etc/postfix/virtual_mailboxes'(virtual_mailboxeswouldthenhaveonedomainperline)NEVERlistavirtualmailboxdomainasa
mydestinationdomain.
shell> postconfe'virtual_mailbox_maps=proxy:mysql:/etc/postfix/mysqlvirtual_mailboxes.cf':
Mapseachandeveryvirtualemailaddresstoamailboxfile,eg.rasmus@webmodelling.commustbemappedtothefolder
webmodelling.com/rasmus,themappingshouldnotcontainthevirtual_mailbox_base,onlythemailboxfolderandtheuserfile/folder.If
usingMaildirformat,thevirtual_mailbox_mapsfilemustappendaforwardslashtothepathnamelike:rasmus@webmodelling.com
webmodelling.com/rasmus/.
shell> postconfe'virtual_mailbox_base=/home/vmail':
Virtual_mailbox_baseisjustafoldertherethemailboxeswillbecreated.Thevirtuallocaldeliveryagentwillprefix
virtual_mailbox_basetoallpathnamesfromvirtual_mailbox_mapstokeepmailboxesinthevirtual_mailbox_basefolder.
shell> postconfe'virtual_uid_maps=static:5000':
SpecifiesthesystemuserthatPostfixusesthendeliveringvirtualmailboxfiles(allfilesmustbelongtoasystemuser,herevmailwith
UserID=5000).
shell> postconfe'virtual_gid_maps=static:5000':
SpecifiesthesystemgroupthatPostfixusesthendeliveringvirtualmailboxfiles(allfilesmustalsobelongtoasystemgroup,here
vmailwithGroupID=5000).
shell> postconfe'proxy_read_maps=$local_recipient_maps$mydestination$virtual_alias_maps$virtual_alias_domains$virtual_mailbox_maps
$virtual_mailbox_domains$relay_recipient_maps$relay_domains$canonical_maps$sender_canonical_maps$recipient_canonical_maps$relocated_maps$transport_maps
$mynetworks$virtual_mailbox_limit_maps':
9. SpecifytouseDovecotLDAforlocaldelivery(insteadofPostfixvirtualdeliveryagent):
1. shell> postconfevirtual_transport=dovecot::
2. shell> postconfedovecot_destination_recipient_limit=1:notethatyouhavetowritedovecot_destination_recipient_limitinsteadofthe
generictransport_destination_recipient_limit.
3. shell> nano/etc/postfix/master.cf:openPostfixmaster.cffileandregisterDovecotLDAservicebyaddingthefollowingline:
dovecotunixnnpipeflags=DRhuuser=vmail:vmailargv=/usr/lib/dovecot/deliverf${sender}d${recipient}
(emailmessagestorasmus@example.comwillbestoredin/home/vmail/example.com/rasmus/Maildir)
disable_plaintext_auth=no:otherwiseIcannotgetGmailPOP3integrationtowork.
namespace{
type=private:thisnamespacecontainsonlytheusersownmailboxes.(therearealsosharedandpublictypes).
separator=.:charforseparatingchildfolders,eg.work.designorwork.programming.
prefix=INBOX.
inbox=yes:thisnamespacecontainstheinbox(thereareonlyoneinbox).
}
protocollda{:weneedtooverwritetheprotocolldasettinginconf.d/01mailstackdelivery.conf
auth_socket_path=/var/run/dovecot/authmaster:UNIXsocketpathtoDovecotLDA.
postmaster_address=root@localhost:hereitmaybebettertouseyourownemailaddress
mail_plugins=sieve
log_path=/home/vmail/dovecotdeliver.log
deliver_log_format=msgid=%m:%$
rejection_reason=Yourmessageto<%t>wasautomaticallyrejected:%n%r
}
authdefault{
user=root
passdbsql{
args=/etc/dovecot/dovecotsql.conf
}
userdbstatic{
args=uid=5000gid=5000home=/home/vmail/%d/%nallow_all_users=yes
}
socketlisten{
master{:mastersocketgivesaccesstouserdbinformationtypicallysotheDovecotLDAcanfindmailboxlocations
path=/var/run/dovecot/authmaster
mode=0600
user=vmail
}
}
}
2. shell> nano/etc/dovecot/dovecotsql.conf:open/createdovecotsql.confinthenanoeditorandaddthefollowing:
driver=mysql
connect=host=127.0.0.1dbname=Postfixuser=mail_adminpassword=MailAdminPassword:thesameMailAdminPasswordas
thenyoucreatedthemail_adminuserforthePostfixdatabaseabove.
default_pass_scheme=PLAIN
password_query=SELECTemailASuser,passwordFROMusersWHEREemail='%u'
3. shell> chmod600/etc/dovecot/dovecotsql.conf:besureonlyrootcanaccessthefilesinceitcontainsyourMailAdminPassword.
4. shell> /etc/init.d/dovecotstop&&sleep5&&/etc/init.d/dovecotstart:restarttheDovecotservertoenabletheconfigurationchanges(as
usuallywait5secondsbetweenstopandstartquatheansilchildprocessbug).
VirtualdomainsTestitworks
Youremailserverisnowreadytohandlehugeamountsofdomainsandemailaddresses,howeverwebettertestsomeofitbeforewecontinueto
enhancetheemailserverwithspamcontrolandsecurity.
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
4/18
4/8/2015
enhancetheemailserverwithspamcontrolandsecurity.
UbuntuEmailServer
1.
2.
3.
4.
5.
6.
shell> mysqlurootpPassword:logontoMySQLserver.
mysql> USEPostfix;
mysql> INSERTINTOdomains(domain)VALUES('example.com');
mysql> INSERTINTOusers(email,password)VALUES('rasmus@example.com','abc');
mysql> quit
shell> postmapqexample.commysql:/etc/postfix/mysqlvirtual_domains.cf:ifthatcommandoutputsexample.com,thenPostfixvirtualdomainsworks
usingMySQL.
7. shell> postmapqrasmus@example.commysql:/etc/postfix/mysqlvirtual_email2email.cf:ifthatcommandoutputsrasmus@example.com,thenPostfix
virtualusersworksusingMySQL.
8. shell> echo"127.0.0.1example.com">>/etc/hosts:resolveexample.comtolocalhost.
9. TestPostfix:
1. shell> telnetlocalhost25:probetheserveronport25(Postfix)tobesurePostfixislistening.
1. Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.:noticetheescapecharacter,ctrl+],shouldyougetinanytroublehere
220Your.Domain.NameESMTPPostfix(Ubuntu)
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
helolocalhost:(moreinfowith ehlolocalhost)
250your.domain.name
mailfrom:root@localhost
2502.1.0Ok
rcptto:rasmus@example.com
2502.1.5Ok
data:beginthedatasection.
354Enddatawith<CR><LF>.<CR><LF>
Subject:Mysecondsubject
Mysecondbody
.:adotonanewlinefollowedbyEnterwillendthedatasection.
2502.0.0Ok:queuedasB58B2102478
quit:
2212.0.0Bye
Connectionclosedbyforeignhost.
10. TestDovecotLDA:(registeredin/etc/postfix/master.cf,sinceitisPostfixthatdecideswhatagentisresponsibleforlocaldelivery)
1. shell> lsl/home/vmail/example.com/rasmus/Maildir/new:thereshouldbeoneemailmessagefile,whichconfirmsthatDovecotLDAis
activatedforlocaldelivery,thatitfunctionsandthatthepathiscorrect(thepathisdefinedusingmail_locationin
/etc/dovecot/dovecot.conf).
11. TestDovecot:(hereusingimapinsteadofpop3justforfun)
1. shell> telnetlocalhostimap
1. Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.
*OK[CAPABILITYIMAP4rev1LITERAL+SASLIRLOGINREFERRALSIDENABLEIDLESTARTTLSAUTH=PLAINAUTH=LOGIN]
Dovecotready.
2. 1loginrasmus@example.comPASSWORD:everycommandneedtostartwithanumber
3. 1OK[CAPABILITYIMAP4rev1LITERAL+SASLIRLOGINREFERRALSIDENABLEIDLESORTSORT=DISPLAY
THREAD=REFERENCESTHREAD=REFSMULTIAPPENDUNSELECTCHILDRENNAMESPACEUIDPLUSLISTEXTENDED
I18NLEVEL=1CONDSTOREQRESYNCESEARCHESORTSEARCHRESWITHINCONTEXT=SEARCHLISTSTATUS]Loggedin :note
thattheanswerstartswiththesamenumberasthecommand.
4. 2list"""*":askforalistofallemailfoldersbelongingtorasmus@example.com.
5. *LIST(\HasChildren)".""INBOX"
2OKListcompleted.
6. 3select"INBOX":selecttheINBOXfolder.Asyoucanseebelow,Ihave15emailsofwhich1isnew(theoneIjustsentabove).
7. *FLAGS(\Answered\Flagged\Deleted\Seen\Draft)
*OK[PERMANENTFLAGS(\Answered\Flagged\Deleted\Seen\Draft\*)]Flagspermitted.
*15EXISTS
*1RECENT
*OK[UNSEEN4]Firstunseen.
*OK[UIDVALIDITY1323581618]UIDsvalid
*OK[UIDNEXT16]PredictednextUID
*OK[HIGHESTMODSEQ1]Highest
3OK[READWRITE]Selectcompleted.
8. 4fetch1all:fetchthefirstemailmessage.
9. *1FETCH(FLAGS()INTERNALDATE"12Dec201112:22:00+0700"RFC822.SIZE394ENVELOPE("Mon,12Dec2011
12:21:37+0700(ICT)""Mysecondsubject"((NILNIL"root""localhost"))((NILNIL"root""localhost"))((NILNIL"root"
"localhost"))NILNILNILNIL"<20111212052145.B06DC101AB3@your.server.domain>"))
4OKFetchcompleted.
10. 5fetch1body[]:thebodyneedstobefetchedexplicitly.
11. *1FETCH(FLAGS(\Seen)BODY[]{394}
ReturnPath:<root@localhost>
DeliveredTo:rasmus@example.com
Received:fromlocalhost(localhost[127.0.0.1])
byyour.server.domain(Postfix)withSMTPidB06DC101AB3
for<rasmus@example.com>Mon,12Dec201112:21:37+0700(ICT)
Subject:Mysecondsubject
MessageId:<20111212052145.B06DC101AB3@mail3.example.tld>
Date:Mon,12Dec201112:21:37+0700(ICT)
From:root@localhost
Mysecondbody
)
5OKFetchcompleted.
12. 6logout
13. *BYELoggingout
6OKLogoutcompleted.
Connectionclosedbyforeignhost.
Ifyoupassedthetests,younowhaveanemailserverthatcanhandleemailaddressesonmultipledomains.AlsoyouareusingMySQLtostorethe
domainsandaddresseswhichmakescreatingnewdomainsandemailaddressesabreezeandservesforeasyintegrationwithotherprograms,eg
thePostfixAdminprogramthatamongotherthingswillgiveyouawebbasedtooltohandledomainsandemailaccountsthroughMySQL.
ConfigureSASL(alternativelyexecuteemailserverinstallationscriptstep3>5)
Currentlywerelyontrustednetworks(specifiedin/etc/postfix/main.cfmynetworksproperty)todecidewhetherPostfixwillallowrelayingan
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
5/18
4/8/2015
UbuntuEmailServer
Currentlywerelyontrustednetworks(specifiedin/etc/postfix/main.cfmynetworksproperty)todecidewhetherPostfixwillallowrelayingan
emailmessage,howeverinsteadwewanttoconfigurePostfixtouseaccountauthenticationtodecidewhethertoallowrelayinganemailmessage
ratherthanwhethertheIPoftheemailclientiswithinourtrustednetworks.
SASL(SimpleAuthenticationandSecurityLayer)isanauthenticationprotocolandPostfixcanuseSASLtoauthenticateemailclients(MUA's)then
theyconnecttoPostfixtoforward(relay)anemailmessage,thatisthenanemailclientasktorelayanemailmessageusingSMTP.
IfwedidNOTconfigurePostfixtouseSASLforSMTPauthentication,wewouldhavetorelyontrustednetworkslikethis:
AnyMUAsendinganemailfromanIPbelongingtothetrustednetworksareALLOWEDtosend.
AnyMUAsendinganemailfromanIPNOTbelongingtothetrustednetworksareREJECTEDtosend.
Ifweallowedeveryonetosend,thenourmailserverwouldbeanopenrelayandfastblacklistedbyotherMTA's.
IfwewanttoallowpeopleonmanydifferentIPstosendemailmessagesthroughourserver,wehavethefollowingsolutions:
AddingtheIPtoourtrustednetworkseachandeverytimeanewpersonwanttosendemail:thatisjusttooheavymaintenance.
UsingtheSMTPafterPOPmethod,whichrequiresaMUAtoPOPbeforeSMTPtotemporarilyaddtheIPtotrustednetworks:thatisnot
supportedbyallMUA's,itisasecurityissueespeciallyondynamicIP'sanditisjustplainawkward.
UsingSASLtoauthenticatetheMUAallowingtheMUAtoforwardemailmessagesevenifit'sIPisnotinthetrustednetworks:thisiseasyto
implement,wellsupportedbyMUA'sandtheindustrystandardoftoday.
Postfixsupports2SASLplugins:CyrusSASLandDovecotSASL,wewilluseDovecotSASLbecausewealreadyuseDovecotforMDAandforLDA
andbecausewehavealreadyinstalledallnecessarypackagesandbecausetheconfigurationismoreeasythanforCyrusSASL.
Let'sgettoit:
1. ConfigureDovecottoprovideSASLauthentication:
1. shell> nano/etc/dovecot/dovecot.conf:loadtheDovecotconfigurationfileinthenanoeditorandmaketheauthdefaultsectionlooklike
this:(newpropertiesinFuchsia)
!includeconf.d/*.conf
pop3_uidl_format=%08Xu%08Xv
log_timestamp="%Y%m%d%H:%M:%S"
imap_client_workarounds=delaynewmailoutlookidlenetscapeeoh
mail_location=maildir:/home/vmail/%d/%n/Maildir
namespace{
type=private
separator=.
prefix=INBOX.
inbox=yes
}
protocollda{
auth_socket_path=/var/run/dovecot/authmaster
postmaster_address=root@localhost
mail_plugins=sieve
log_path=/home/vmail/dovecotdeliver.log
deliver_log_format=msgid=%m:%$
rejection_reason=Yourmessageto<%t>wasautomaticallyrejected:%n%r
}
authdefault{
user=root
mechanisms=plainlogin:plainisthestandardverbforunencrypted(OutlookExpressexpectslogininstead).
passdbsql{
args=/etc/dovecot/dovecotsql.conf
}
userdbstatic{
args=uid=5000gid=5000home=/home/vmail/%d/%nallow_all_users=yes
}
socketlisten{
master{
path=/var/run/dovecot/authmaster
mode=0600
user=vmail
}
client{
path=/var/spool/postfix/private/auth:tellsDovecotwheretocommunicatewithPostfixauthentication.
mode=0660:tellsDovecotthatthereareread&writeaccess.
user=postfix:tellsDovecottousethepostfixuserforaccess.
group=postfix:tellsDovecotusethepostfixgroupforaccess.
}
}
}
2. shell> /etc/init.d/dovecotstop&&sleep5&&/etc/init.d/dovecotstart:restarttheDovecotservertoenabletheconfigurationchanges(as
usuallywait5secondsbetweenstopandstartquatheansilchildprocessbug).
2. ConfigurePostfixtousetheSASLauthenticationprovidedbyDovecot:
1. shell> postconfe'smtpd_sasl_type=dovecot':specifytheSASLplugintouse,hereDovecotSASL(asopposedtoCyrusSASLwhichis
default).
2. shell> postconfe'smtpd_sasl_path=private/dovecotauth':thispathisrelativeto/var/spool/postfix(notethatprivate/authwas
automaticallychangedtoprivate/dovecotauththeninstallingthedovecotpostfixpackage.AlsoItriedtochangeitbackto
3.
4.
5.
6.
7.
private/authbutIwouldthengetfatal:noSASLauthenticationmechanismsin/var/log/mail.errandalso telnetlocalhost25would
disconnect).
shell> postconfe'smtpd_sasl_auth_enable=yes':enabletheuseofSASL.Ifthisvalueisno(default),thenonlyMUA'sontrustednetworks
willbeabletorelayemailmessages.
shell> postconfe'smtpd_recipient_restrictions=permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination':herewespecifytopermit
relayforMUA'sthatareeitherauthenticatedusingSASLorisonourtrustednetworksandtorejectallotherMUA'storelay.
shell> postconfe'broken_sasl_auth_clients=yes':supportforolderMUA'slikeOutlookuptoversion2003andOutlookExpressupto
version6withanobsoleteversionoftheAUTHcommand.Defaultvalueisno,howeverIguessthereisnosecurityriskinvolved.
shell> postconfe'smtpd_tls_auth_only=no':wehavenotconfiguredTLSyet,soifthissettingissettoyes,theSASLauthenticationwould
fail.
shell> servicepostfixreload:reloadtheconfiguration.
SASLTestitworks
Whatweneedtotestis:
ThatweareNOTallowedtorelayemailmessageswithoutloggingin.
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
6/18
4/8/2015
UbuntuEmailServer
ThatweareNOTallowedtorelayemailmessageswithoutloggingin.
ThatweCANloginandthatwearethenallowedtorelayemailmessages.
Torunthistest,youneedtotelnetfromaremoteboxashelloneg.yourWindowsorUbuntubox.DONOTtrytotelnetfromthesameOSthat
hostyourmailserver,theideaistogetanIPoutsideofthePostfixtrustednetworks.(Ifyourunthewholetutorialonyourdevmachine,youcan
useeg.VirtualBoxtofastsetupavirtualmachinetotestfrom).
1. FirstconfirmthatPostfixannouncestheSASLcapabilityandthatyoucansendemailthatdoesnotneedtoberelayed:
1. remoteshell> telnetMailServerIP25
1. Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.
220Your.Domain.NameESMTPPostfix(Ubuntu)
2. ehlolocalhost
3. 250your.server.domain
250PIPELINING
250SIZE10240000
250VRFY
250ETRN
250AUTHPLAINLOGIN:Postfixannouncesthatitsupportsauthenticationusingplainorloginmechanisms
250AUTH=PLAINLOGIN:Postfixannouncesittwicebecausebroken_sasl_auth_clientsissettoyes.
250ENHANCEDSTATUSCODES
2508BITMIME
250DSN
4. mailfrom:root@localhost
5. 2502.1.0Ok
6. rcptto:rasmus@example.com:rasmus@example.comisalocaladdress(rememberweaddedthisdomainandemailaddressabove
thentestingvirtualdomains).
7. 2502.1.5Ok
8. data
9. 354Enddatawith<CR><LF>.<CR><LF>
10. Subject:subremote1
11. bodyremote1
12. .
13. quit
14. 2212.0.0Bye
Connectionclosedbyforeignhost.
2. localshell> lsl/home/vmail/example.com/rasmus/Maildir/new:checkthemailhasarrived(thiscommandshouldbeexecutedonthesameOS
thathostyourmailserver).
2. Secondconfirmthatyoucannotrelayanemailmessagewithoutloggingin:
1. remoteshell> telnetMailServerIP25
1. Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.:noticetheescapecharacter,ctrl+],youaregoingtoneedit
220Your.Domain.NameESMTPPostfix(Ubuntu)
2. mailfrom:root@localhost
3. 2502.1.0Ok
4. rcptto:rasmus@webmodelling.com:rasmus@webmodelling.comisnotalocalhostaddress.
5. 5545.7.1<rasmus@webmodelling.com>:Relayaccessdenied:indeedPostfixcorrectlyrejectedtorelaytheemailmessage.
6. ctrl+]:pressctrl+]toescape,itisnotpossibletocontinue.
7. ^]
8. telnet> quit
9. Connectionclosed.
3. ThirdconfirmthatyoucanlogonandthatPostfixaccepttorelaythemessage:
1. shell> aptgetinstallopenssl:installopenssltobase64encodeyouremailcredentials.
2. shell> printf'\0%s\0%s''username''password'|opensslbase64:createabase64encodedvalueofyourusernameandpasswordtousefor
SASLauthenticationbelow.
3. remoteshell> telnetMailServerIP25:again,besuretousearemoteshell.
1. Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.
220Your.Domain.NameESMTPPostfix(Ubuntu)
2. AUTHPLAINAHJhc211c0BleGFtcGxlLmNvbQBhYmM=:'AHJhc211c0BleGFtcGxlLmNvbQBhYmM='isthebase64encodedvalueof
rasmus@example.comabc(Iuseabcforpassword)besuretocreateyourownbase64encodingofthelocalemailaccountyou
willusetosendfrom.
3. 2352.7.0Authenticationsuccessful:ThereyougotitSASLworks!
4. mailfrom:rasmus@example.com
5. 2502.1.0Ok
6. rcptto:rasmus@webmodelling.com:useoneofyourownemailaccounts.
7. 2502.1.5Ok
8. data
9. 354Enddatawith<CR><LF>.<CR><LF>
10. Subject:subremote1
11. bodyremote1
12. .
13. quit
14. 2212.0.0Bye
Connectionclosedbyforeignhost.
4. Confirmthatyouhavereceivedtheemail(inmycaserasmus@webmodelling.com).
ConfigureTLS(alternativelyexecuteemailserverinstallationscriptstep3>6)
WhileSASLprovidesamechanismtoauthenticateremoteusersbyusernameandpasswordthentheytryrelayanemailmessagethroughtheemail
server,bothusernameandpasswordaresentinplaintextandcouldbeeasilyinterceptedandstolen.
UsingTLS(TransportLayerSecurity)wecanencryptthecommunicationbetweentheemailclientandtheemailserver,sothatifthe
communicationisintercepted,thecredentialswillnotbeinplaintext.
Thereare2waystosecureaprotocolwithTLS:
Theclientconnecttoaserverssecureportemailtypically993(imaps)or995(pop3s)andimmediatelybeginanencryptedhandshake.
Theclientconnecttoaserversplaintextportemailtypically25(smtp),110(pop3)or143(imap)andbeginanunencryptedhandshake.
IftheserverrespondtheSTARTTLScapability,thenthesubsequentcommunicationcanbeencryptedwhichincludestheauthentication
process(whereusernameandpasswordaresent).
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
7/18
4/8/2015
UbuntuEmailServer
process(whereusernameandpasswordaresent).
RegardlessofwhichTLSmethodisapplied,theservermustsentapublickeytotheclient,whichtheclientwillthenusetoencrypttherestofthe
session.Onlytheserverthathavethecorrespondingprivatekeywillbeabletodecrypt.However,theclientwillneedtotrustthatitisconnected
totherightserver,thereforetheserverdisplaysasignedcertificate,whichtheclientwillautomaticallyacceptifthesigningisdonebyatrusted
authority,whileifitisaselfsignedcertificate(whichwewilldo)thentheclientwillasktheuserwhethertotrustit.
Allinallwethereforeneed:
Aprivatekey
Asignedpublickeycertificate(createdfromtheprivatekey)
Createthe2TLSkeyfiles
Dovecotmaylikelyalreadyhavecreatedthe2keysin/etc/ssl/certs/dovecot.pem&/etc/ssl/private/dovecot.pem,howeverwewanttocreateour
own
1. shell> cd$HOME:changecurrentdirectorytoyourhomedirectorytomakethekeyfilesthere.
2. shell> opensslgenrsades3outserver.key1024:use opensslgenrsatogenerateatripleDES(des3)encryptedprivatekeyfile(server.key).You
willbepromptedforapassphraseforthetripleDESencryption.
3. Unencrypttheprivatekey:(OtherwisewewouldhavetomanuallywritethepassphraseeachtimePostfixstartsup,whichisnotpractical)
1. shell> opensslrsainserver.keyoutserver.insecure:use opensslrsatocreateanunencryptedversionoftheprivatekey.
2. shell> mvserver.keyserver.key.secure:storetheencryptedprivatekeyasserver.key.secure.
3. shell> mvserver.key.insecureserver.key:renametheunencryptedprivatekeytoserver.key.
4. shell> opensslreqnewkeyserver.keyoutserver.csr:use opensslreqtogenerateaCertificateSigningRequestfile(server.csr)usingtheprivate
key(server.key).Youwillbepromptedforrelevantinformationtobeincorporatedintoyourcertificatesigningrequest:(youdon'tneedto
answerthemall)
1. CountryName(2lettercode)[TH]:TH:THforThailand(whereIlive).
2. StateorProvinceName(fullname)[SomeState]:Nonthaburi:morepreciselyIliveinNonthaburi.
3. LocalityName(eg,city)[]::Idon'tanswer.
4. OrganizationName(eg,company)[InternetWidgitsPtyLtd]:FD:FDforFavouriteDesign.
5. OrganizationalUnitName(eg,section)[]::Idon'tanswer.
6. CommonName(eg,YOURname)[]:your.server.domain:thisisthemostimportantquestiontoanswer.
7. EmailAddress[]:rasmus@webmodelling.com
8. Achallengepassword[]::Idon'tanswer.
9. Anoptionalcompanyname[]::mygood,thenwillitend.
5. shell> opensslx509reqdays365inserver.csrsignkeyserver.keyoutserver.crt:use opensslx509tocreatea(self)signedcertificatefile(server.crt)
thatisvalidfor365daysusingthesigningrequestfile(server.csr)containingyourorganizationsinformationandusing(server.key)
Signatureok
subject=/C=TH/ST=Nonthaburi/O=FD/CN=RasmusRummel
GettingPrivatekey
6.
7.
8.
9.
shell> mvserver.key/etc/ssl/private/:movetheprivatekeyfileto/etc/ssl/private/.
shell> mvserver.crt/etc/ssl/certs/:movethecertificatefileto/etc/ssl/certs/.
shell> chownroot:root/etc/ssl/private/server.key:setfullownershiptorootfortheprivatekeyfile.
shell> chmod600/etc/ssl/private/server.key:besurethatonlyroothaveaccesstotheprivatekeyfile(sinceitisnotencrypted).
ConfigurePostfixtoofferTLS
1. shell> postconfe'smtp_tls_security_level=may':securitylevelfortheSMTPclient.'may'meansthatPostfixwilluseTLSiftheremoteSMTP
serversupportsit(othervaluesare'none','encrypt''fingerprint','verify'and'secure').
2. shell> postconfe'smtpd_tls_security_level=may':'securitylevelfortheSMTPserver.may'meansthatPostfixwillannounceSTARTTLScapability
toclients,butnotrequirethatclientsuseTLS(othervaluesare'none'and'encrypt',encryptwillrequiretheclienttouseTLS).
3. shell> postconfe'smtpd_tls_auth_only=no':thiswillallowemailclientstologonwithoutencrypting.Ifyouwanttoforceemailclientstoenable
encrypting,youneedtosetthisvaluetoyesand ehlolocalhostwillnotanylongershowtheAUTHPLAINcapability(bepreparedtohelp
peoplewithemailaccountsonyourservertosetupencryptionintheiremailclients).
4. shell> postconfe'smtpd_tls_key_file=/etc/ssl/private/server.key':
5. shell> postconfe'smtpd_tls_cert_file=/etc/ssl/certs/server.crt':
6. shell> postconfe'smtpd_tls_loglevel=1':loglevelsrunfrom0(verylittlelogging)to4(extremelogging).
7. shell> postconfe'smtpd_tls_session_cache_timeout=3600s':defineaTLSsessioncachetoavoidmultiplerelativelyexpensivekeyexchangesand
clearthecacheeveryhour.
8. shell> postconfe'tls_random_source=dev:/dev/urandom':
TLSTestitworks
1. shell> telnetMailServerIP25:again,besuretousearemoteshell.
1. Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.
220Your.Domain.NameESMTPPostfix(Ubuntu)
2. ehlolocalhost
3. 250mail6.example.tld
250PIPELINING
250SIZE10240000
250VRFY
250ETRN
250STARTTLS :PostfixannouncesSTARTTLScapability
250AUTHPLAINLOGIN
250AUTH=PLAINLOGIN
250ENHANCEDSTATUSCODES
2508BITMIME
250DSN
4. quit:it'stoodifficulttoencryptonthecommandline,sojustquit.
5. 2212.0.0Bye
Connectionclosedbyforeignhost.
2. Letstestwitharealemailclientonaremotemachine,eg.yourWindowsorUbuntudevbox
1. Onyourdevbox,mapourtestdomain,example.com,toyouremailserversIPusingthedevboxhostsfile:
OnanUbuntudevbox:
1. devboxshell> echoe"\nYouEmailServerIPexample.com">>/etc/hosts:thee"\n"istostartonanewline.
2. devboxshell> pingexample.com:besureyougetYourEmailServerIP.
1. OnaWindows7devbox:
1. OpenC:\Windows\System32\drivers\etc\hostsinyourfavouritetexteditorandaddthefollowingline:
YourEmailServerIPexample.com:eg.formeitis 192.168.1.72example.com
2. devboxshell> pingexample.com:besureyougetYourEmailServerIP.
2. Onyourdevboxopenanemailclient,eg.OutlookExpressorThunderbird.
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
8/18
4/8/2015
UbuntuEmailServer
2. Onyourdevboxopenanemailclient,eg.OutlookExpressorThunderbird.
3. SetyouremailclienttouseSTARTTLS:(hereThunderbird)
1.
Createanewaccountforrasmus@example.com.
2.
AddMailAccount.
3.
MailAccountSetup
4.
IMAP&SMTPareautomaticallyconfiguredtouseSTARTTLS.
5.
PresstheCreatebuttonandwaitforThunderbirdtotestthepassword.
6.
Successaccountcreated.AlsonotetheOutgoingServerisexample.comusingrasmus@example.comfor
authentication.
4. Useyouremailclienttofetch(usingIMAP)emailmessagesfromyouremailserver:(hereThunderbird)
1.
IntheleftpanelselectthenewaccountandthenintherightpanelclickonReadMessages.
2.
Acceptthecertificate(thisistheDovecotdefaultcertificate).
3.
SuccessearliertestmailsfetchedusingTLS.
5. Useyouremailclienttorelayanemailmessagethroughyouremailserverfromyourtestaddress(formeitisrasmus@example.com)
tooneofyourrealemailaddresses(formeitisrasmus@webmodelling.com):(hereThunderbird)
1.
Writeanemailtooneofyourrealemailaddresses.
2.
Dreadfulunknownerrorhoweverthereasonisthemissingcertificate.
3.
Acceptthecertificateagain(actuallythisisanewcertificate,theonewemadeforSMTP).
4.
SuccessmailrelayedusingTLS(noteyourtestservercannotsenddirectlytogmailbecausegmailrefusesto
receiveemailmessagesifsendersIPaddressanddomainnamedoesnotmatch,seemorehere(thisproblemwillgoawaythen
youpublishyouremailserverforproductionwithdomainnamesacknowledgedbypublicdns)).
Ifyoupassedthetests,younowhaveasecurefullworkingemailserver,congratulations.
Installspamcontrol
UNDERCONSTRUCTION
InstallSquirrelmail
Squirrelmailisamongthemost,ifnotthemost,popularwebmailprogramsforlinuxmachines(andcanalsobeinstalledonwindows).
InstallApache(alternativelyexecuteemailserverinstallationscriptstep3>7)
Webmailneedstorunontopofawebserver,thereforeweneedtoinstallApachefirst(ifyoualreadyhaveApacheonyoursystem,eg.ifyouhave
aLAMPstack,youshouldskipthisstep).
1. shell> aptgetinstallapache2:installApache.
2. shell> /etc/init.d/apache2restart:restartApache.
Thatwaskindofeasy!
InstallSquirrelmail(alternativelyexecuteemailserverinstallationscriptstep3>8)
1. shell> aptgetinstallsquirrelmailsquirrelmailcompatibilityphppearphpdb
squirrelmail:thewebmailprogramwithsupportforIMAP&SMTP.
squirrelmailcompatibility:supportforplugins.
phppear:MAYBEnecessaryforSquirrelmailtorunonApache(SquirrelmailisaPHPprogram).phppearisnecessaryforphpdb
though.
phpdb:MAYBEnecessaryforSquirrelmailtorun(thoughIthinkSquirrelmaildonotaccessMySQLonlyPostfix&Dovecot)
2. shell> lns/etc/squirrelmail/apache.conf/etc/apache2/conf.d/squirrelmail.conf:SquirrelmailcomeswithapredefinedApacheconfigurationfilewhich
wesymlinkto/etc/apache2/conf.dthatwillenableApachetoloadtheconfiguration.
3. shell> /etc/init.d/apache2restart:restartApachetostarttheSquirrelmailweb.
NotethatSquirrelmailisnotusingSASLandthereforedependson:
BeinginstalledonthesameserverasPostfix.
/etc/postfix/main.cf smtpd_recipient_restrictionsMUSTinclude permit_mynetworks.
OtherwiseyouwillgetTransactionfailed5545.7.1:RelayaccessdeniedeverytimeyoutrytosendanemailfromSquirrelmail.
WebmailTestitworks
1. Openabrowseronaremotemachineandputinthefollowingurl: http://YouEmailServerIP/squirrelmail:youshouldseetheloginpage.
2. Loginwiththeuserwehaveusedthroughoutthetutorial(formeitisrasmus@example.comwithpasswordabc):youshouldnowcometo
yourinboxanditshouldshowtheemailmessageswehavetestsendearlier.
3. Composeatestemailinsquirrelmailandsendittooneofyourownemailaddresses(inmycaserasmus@webmodelling.com):aftersome
timeyoushouldreceivetheemail(ifithavenotarrivedwithinhalfanhour,itislikelynottoarrive).
Ifyoupassedthetest,congratulationsyouwebmailisfunctioning.
AppendixAccessSquirrelmailonmultiplecustomurls
Sincethisemailserversupportsvirtualdomains,youmaywanttoaccessSquirrelmailondifferentcustomurls,herewewillconfigureSquirrelmail
tobeaccessibleon2testdomains:
http://webmail.test1.com
http://webmail.test2.com
Alsoweneed2machinesforthetest:
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
9/18
4/8/2015
UbuntuEmailServer
Youremailservermachine.
Aremotemachine,eg.yourWindowsorUbuntudevbox,onwhichtheabovedomainswillresolvetoYourEmailServerIP.
1. Onyouremailservereditthesquirrelmail.conffiletomaptowebmail.test1.comandwebmail.test2.com:
1. shell> nano/etc/apache2/conf.d/squirrelmail.conf:loadsquirrelmail.confinthenanoeditorandaddthefollowing:
<VirtualHost*>:*meansthatthisvirtualhostisdefinedforallIPaddresses.
ServerNamewebmail.test1.com:thisvirtualhostmapstowebmail.test1.com
ServerNamewebmail.test2.com:thisvirtualhostmapstowebmail.test1.com
DocumentRoot/usr/share/squirrelmail:thisvirtualhosthavedocumentrootin/urs/share/squirrelmail
</VirtualHost>
2. Pressctrl+xandthenytosaveandreturntoprompt.
3. shell> /etc/init.d/apache2restart:restartApachetoloadthechangedconfiguration.
2. Onyourdevboxmapourtestdomains,test1.com&test2.com,toyouremailserversIPaddressbyaddingthetestdomainstothedevbox
hostsfile:
OnaWindows7devbox:
1. OpenC:\Windows\System32\drivers\etc\hostsinyourfavouritetexteditorandaddthefollowinglines:
YourEmailServerIPwebmail.test1.com:eg.formeitis 192.168.1.72test1.com
YourEmailServerIPwebmail.test2.com:eg.formeitis 192.168.1.72test2.com
2. devboxshell> pingwebmail.test1.com:besureyouseeYourEmailServerIP(inmycase192.168.1.72)
OnanUbuntudevbox:
1. devboxshell> echoe"\nYourEmailServerIPwebmail.test1.com">>/etc/hosts:echoe"\n"willinsertanewline.
2. devboxshell> echo"YourEmailServerIPwebmail.test2.com">>/etc/hosts
3. devboxshell> pingwebmail.test1.com:besureyouseeYourEmailServerIP(inmycase192.168.1.72)
3. Startawebbrowseronyourdevboxandnavigatetowebmail.test1.com:youshouldseeSquirrelmailloginpage.
4. Navigatethesamewebbrowsertowebmail.test2.com:youshouldagainseeSquirrelmailloginpage.
Appendix:Management&DebuggingCommands
Thefollowingisasmallcollectionofcommandstoempoweryousomewhatincaseofproblemseg.ifunderattack.
shell> tail30/var/log/mail.log:displaythelast30linesinthemaillog.
shell> tail30/var/log/mail.err:displaythelast30linesinthemailerrorlog.
shell> tail1000/var/log/mail.log|grepi':to=<.*@webmodelling\.com>,'|less:focusthelogondeliveriestowebmodelling.com.
shell> tail1000/var/log/mail.log|grepi':from=<.@webmodelling\.com>,'|less:focusthelogonemailssendbywebmodelling.com.
Workingwiththemailqueue
ThepostfixmailqueueisaqueueofmailmessagesthatPostfixhavenotyetdelivered.Thepostfixmailqueueisactuallyconsistingofseveralsub
queues.Messagesaremovedbetweenthesesubqueuesbythequeuemanagerthatalsoisresponsiblefordeliveringthemessages:
incomingqueue:thenamessagearrivesatthepostfixserver,thecleanupservicewillwritethemessagetoafileownedbythepostfix
userandmaskit0600.Thenthemessageisfinishedwrittentofile,thecleanupservicechangethefilemaskto0700.Iftheactivequeueis
notfull,thequeuemanagerwillperiodicallyscantheincomingqueue(allthenewmessagefiles)andmovefileswithmask0700tothe
activequeue.Ifmailsarecominginfasterthanthequeuemanagercanmovethemfromincomingtoactive,theincomingqueuewillgrow.
activequeue:messagesintheactivequeuearereadytobesent(runable)butnotnecessarilyintheprocessofbeingsent(running).While
theincoming,deferred,maildropandholdqueuesareonlyfilesondisknotoccupyingmemory,theactivequeueisalsoadatastructurein
memoryownedbythequeuemanagerprocess.Becausemessagesintheactivequeuearerepresentedinmemory,thereisalimittohow
manymessagescanbeholdintheactivequeueatwhichpointthequeuemanagerstopscanningtheincomingandthedeferredqueues
(sincenomoremessagescanbemovedtotheactivequeue).
deferredqueue:ifdeliveryfailedforoneormorerecipientsofamessage(eg.arecipientaddresscouldnotbevalidated),themessage
willbemovedtothedeferredqueueandassignedacoolofftime(between minimal_backup_timeand maximum_backoff_time)before
whichthequeuemanagerwillnotmovethemessagebackintotheactivequeue.
holdqueue:theadministratorcancreaterules(eg.basedoncontentinheadersorbody)thatwillmovemessagestotheholdqueue
outsideofnormalprocessing.Amessageinholdisnothandledbythequeuemanagerbutneedstobemanuallymovedtoanotherqueue.
postsuperrwillmovemessagesfromholdtomaildrop,while postsuperHwillmovemessagesfromholdtodeferred.
maildropqueue:containerformessageslocallysubmittedusingpostfixsendmail.Themaildropqueueisnotconsideredpartofthepostfix
mainqueueasmessageshavenotyetbeencheckedandrewrittenbythecleanupservice.Messagesaremovedtoincomingqueuebythe
pickupservicefromwhichpointonthecleanupserviceistakingover.
NotethatthequeuemanagerismainlysloweddownbyI/Ooperations(movingthemessagesbetweenqueues)andbytransportlookupqueries.
shell> mailq:listallmailsinthemailqueue(maildrop,incoming,active&deferred).
shell> mailq|grep"webmodelling.com":displayallmessagescontaining"webmodelling.com".
Folderactions:
shell> lsl/var/spool/postfix:listallfoldersinvolvedwiththemailqueue.
shell> find/var/spool/postfixtypef|wcl:veryfastwaytoapprocimatelycountfilesinahugemailqueue(theresultisnotprecise
becauseotherfoldersthanthe4mainqueuefoldersarecounted).
shell> find/var/spool/postfix/deferredtypef|wcl:countmessagesinthedeferredqueue.
shell> grep"webmodelling.com"/var/spool/postfix/deferred/*|wcl:countmessagesinthedeferredqueuecontaining"webmodelling.com".
postsuper
shell> postsuperdMESSAGEID:deleteamessagebyit'smessageID.
shell> postsuperdALL:deleteallmailsinthequeue(typicallyusedthenyourqueueisfloodedwitheg.spam).
shell> postsuperdAlldeferred:deleteallmailsinthedeferredqueue.
shell> postsuperhMESSAGEID:movemessagewithID=MESSAGEIDfromincomingqueuetoholdqueue.
shell> postsuperrMESSAGEID:requeuemessagewithID=MESSAGEIDfromanyqueuetoincomingqueue.
shell> postsuperhALL:moveallmessagesfromincomingqueuetoholdqueue.
shell> postsuperrALL:requeueallmessagesfromanyqueuetoincomingqueue.
Deletemessagesfromaspecificdomainoruserormessagescontainingaspecifictext:
shell> mailq|grep'webmodelling.com'|awk'{print$1}'|postsuperd:deleteallmessagescontaining'webmodelling.com'.
shell> mailq|grep'webmodelling.com'|awk'{printsubstr($1,0,12)}'|postsuperd:sometimesthemessageIDfieldhaveastar(*)
appended,whichmustberemovedbeforepostsuperwillrecognisethemessageIDfield.
postqueue:
shell> postqueuep
shell> postqueuef:flushallmailsinthedeferredqueue,thatis:moveallmessagestotheactivequeuetotrytodeliverallmails
immediately.Thisismostoftenabadideaasmailsinthedeferredqueuearetherebecauseofdeliverytrouble,soiftryingtodeliver
themallatonce,theactivequeuemayeasilybecomecongestedandmessagesintheincomingqueuemaywaitalongtimebefore
theycanbedelivered.
postcat:
shell> postcatqMESSAGEID:readallheadersofathemessagewithID=MESSAGEID.Thisisveryusefultoidentifythereasonwhya
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
10/18
4/8/2015
UbuntuEmailServer
shell> postcatqMESSAGEID:readallheadersofathemessagewithID=MESSAGEID.Thisisveryusefultoidentifythereasonwhya
messageisinthedeferredqueue.
qshape:(qshapetutorial)
shell> qshape:showspostfixqueuecontentinatabularformorderingdestinationdomainsafteroccurrenceontheverticalaxisand
queueagealongthehorizontalaxis.
shell> qshapes:showssenderdomainsinsteadofdestinationdomainsusefultoidentifyfromwhichdomainsspamarebeingsent.
shell> qshapedeferred:showswhichdestinationshavebeenunabletobedelivered.
shell> qshapeactive:showswhichdestinationsareintheprocessoftryingtobedelivered.
shell> postconfemaximal_queue_lifetime=1d:settingthequeuelifetimeto1day,whichmeansthatamessageundeliverableafter1daywillbe
returnedtosenderwithan"undelivered"notice.Thedefaultqueuelifetimeis5days.Thequeuelifetimevaluecanbesetinseconds(s),
minutes(m),hours(h),days(d)andweeks(w).(reloadpostfixaftersettingthisproperty servicepostfixreload).
MailLog
Logfiles:(Postfixlogsthroughsyslog,/etc/syslog.conf,onUbuntuthisisdefaultto/var/log)
/var/log/mail.log:PostfixsendsALLlogmessagestothisfile.
/var/log/mail.err:Postfixalsosendserrormessagestothisfile(becauseitcanbedifficulttofindtheerrormessagesinmail.log)
/var/log/mail.warn:Postfixalsosendswarningmessagestothisfile.
Usethetailcommandtoviewthelogfiles:
shell> tail30/var/log/mail.log:printthelast30messagestoscreen.
shell> tailf/var/log/mail.log:keepprintingnewmessagestoscreeninrealtime.
Postfixlogformat:(Postfixconsistofseveralcomponentsthateachlogstomail.logintheirownformat,howeverallentriesconsistof4
elementaryparts:
1.
2.
3.
4.
Datetime:eg.Mar1312:54:07.
Hostname:eg.mail1.
ComponentID:eg.postfix/smtpd[27559]:(otherexamplesarepostfix/master[932]:orDovecot:oramavis[2021]:).
Message:thisisverydifferentdependingonthecomponent(Iamnotsureifthesamecomponentalwayshavethesameformat)
Elementsofthepostfix/smtpdcomponentlog:
delaysa/b/c/d:
a:timebeforequeuemanager,includingmessagetransmission.
b:timeinqueuemanager.
c:connectionsetupincludingDNS,HELOandTLS.
d:messagetransmissiontime.
Myemailserverissendingalotofspamhelp
Ifyouremailserverstartstosendalotofspam,youremailserverwillbeblacklistedbydifferentemailblacklistserversandyoucannotanylonger
sendemailtoanyoneusingtheseblacklistservers.
Tofighttheproblem,youcanamongotherstryto:
Testthatyouremailserverisnotanopenrelay:
Gotohttp://abuse.net
Makeanaccountandtestifyouremailservercanbeusedasanopenrelay
Setyourlogleveltomaximum
Focusonacertainlog
Ifyouhostmanywebsites,itcanbeverydifficult,eg.ifthereareanoldversionofJoomla,Mambo,Wordpressetc.,someonemaybeableto
breakinanduploadamailsendingscript.
Appendix:BasicConcepts
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
11/18
4/8/2015
UbuntuEmailServer
MTA:MailTransferAgent:AnMTAreceivesandsendsoutmail.PostfixisthedefaultMTAonUbuntu(thoughExim4isalsointhemain
repository).
MDA:MailDeliveryAgent:AnMDAmakesmessagesreceivedbyMTAavailablefordownloadusingeg.IMAPorPOP3.Dovecotisthe
defaultMDAonUbuntu(thoughCourierwithsupportforexternaldatabaseserverisalsointhemainrepository).SinceDovecotsupports
IMAP&POP3,DovecotisalsocalledanIMAP&POP3server.
MUA:MailUserAgent:AMUAistheemailprogramyouusetocreateemailmessagesandtoreceiveandreadthem,eg.OutlookExpressor
Thunderbird.
LDA:LocalDeliveryAgent:ThenanMTAdecidesthatitisitselfthefinalMTAdestinationforanemailmessage,theMTAinsteadof
forwardingtheemailmessagetoyetanotherMTAneedstostoretheemailmessageonlocalstorage.Postfixcanstoreanemailmessageif
thestorageformatiseithermboxorMaildir,howevertheMTAcanalsoletanLDAhandlethelocalstorage,eg.DovecotLDAisaPostfix
pluginthathandlesdeliveringemailmessagesfromthePostfixservertothelocalstoragemedia.
IMAP::HighbandwithprotocolforMUAtodownloademailmessagesfromMDA.TypicallyemailmessagesareonlycachedontheMUA
(alsoothergoodstuff).
POP3::LowbandwithprotocolforMUAtodownloademailmessagesfromMDA.TypicallyemailmessagesaredownloadedtotheMUAand
deletedontheserverbytheMDA.
SMTP:SimpleMailTransferProtocol:ProtocolfortransferingemailmessagesfromMUAtoMTAandfromMTAtoanotherMTA.
Mailbox:Amailboxisanemailmessagestorageformat.ThetwomostpopulararemboxandMaildir(bothsupportedbyPostfixfordirect
localdeliverywithoutusinganLDA).mboxstoresemailmessagesinonebigfileforeachemailaccountwhileMaildirstoreseachemail
messageinitsownfile.
SASL:SimpleAuthenticationandSecurityLayer:SASLisanSMTPAuthenticationprotocol/plugin.Postfixsupports2SASLimplementations,
CyrusSASL&DovecotSASL.
Appendix:Relevantlinks
Postfixmanuals
DebianPackagedocumentation
Postfixconfigurationproperties(main.cf)
Dovecotconfigurationproperties
Dovecotexplained
PostfixVirtualDomainHostingHowtoofficialandgood
HowtoconfigurePostfixforvirtualdomainsverygood
PostfixdocumentationforMySQLmapping
Appendix:Squirrelmailinthai
Firstoff:sorryforspammingwithanappendixthatiswithoutinterestforthemajority,howeverpartlyIalsousethispageaspersonal
documentationandpartlythelogicisapplicableforotherlessprominentlanguagesaswell.
ConfigureSquirrelmailtodisplaythaicharacterscorrectthenemailisnotarrivinginutf8:
1. In/usr/share/squirrelmail/functions/i8n.php:
1. ChangetheUScharsetfromiso88591totis620:(tis620isthethaicharacterset)
#$languages['en_US']['CHARSET']='iso88591':outcommentthisrecord.
$languages['en_US']['CHARSET']='tis620';:insertthisrecordbelowtherecordjustoutcommented.
2. Thethailabeltranslationsaredefaultoutcommentedbecauselessthan50%istranslated,howeverwewanttousethem:
Searchthei8n.phpfilefor $languages['th_TH']['NAME'] anduncommentthe4recordsdefiningthethailanguage.
2. In/etc/squirrelmail/config.php:
#$squirrelmail_default_language='en_US':outcommentthisrecord.
#$default_charset='iso88591':outcommentthisrecord.
$squirrelmail_default_language='th_TH';:insertthisrecordbelowthe2justoutcommentedrecords.
$default_charset='tis620';:andtheninsertthisrecordalso.
Appendix:Commonerrorsandsolutions
1. Dovecotunknowndatabasedrivermysql.
Reason:Ifyouhavetheaboveerror1,youhaveforgottoaddmysqlsupportfordovecot.
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
12/18
4/8/2015
UbuntuEmailServer
Solution:Installthedovecotmysqlpackage:
1. shell> aptgetinstalldovecotmysql.
2. Dovecotfatal:pipe_command:execvp/usr/local/libexec/dovecot/deliver:Nosuchfileordirectory.
Reason:Ifyouhavetheaboveerror2,thenDovecotLDAisregisteredwithPostfixinmaster.cfbutwithawrongpath.Ithink
/usr/local/libexec/dovecot/deliveristheoldpathtoDovecotLDAandthereforemanyguidesanddocumentationwillspecifythatpath.The
dovecotpostfixpackageversion2.0.13storesDovecotLDAin/usr/lib/dovecot/deliver.
Solution:RegisterDovecotLDAwiththerightpath:
1. shell> sedie"/\/usr\/local\/libexec\/dovecot/,s/local\/libexec/lib/"/etc/postfix/master.cf:changethepathtoDovecotLDA.(Youcanalsoopen
/etc/postfix/master.cfinnanoandchangethepaththereifyoudon'tlikethesedcommand).
2. shell> /etc/init.d/postfixrestart:makethenewpathactive.
3. Dovecotdovecot:master:Error:service(anvil):Socketalreadyexists:/var/run/dovecot/anvil.
Reason:Thisisaknownbugindovecotcommon2.0.13,seehere,thattheanvilchildprocessisslowtocloseandthereforemayblockDovecot
startup.
Solution:IusethefollowingworkaroundthatinsteadofrestartingDovecot,IfirststopDovecotthenwait5secondsandthenstartDovecot(it
seemstoworkeverytime).
1. shell> /etc/init.d/dovecotstop:stopthedovecotserverandWAIT5secondshopingthattheanvilchildprocessisalsostopping
2. shell> /etc/init.d/dovecotstart:startthedovecotserver
3. shell> nmaplocalhost:checkifpop3&imapareup,ifnotthenstopDovecotandagainwaitsometimebeforetryingtostartDovecot.
shell> /etc/init.d/dovecotstop&&sleep5&&/etc/init.d/dovecotstart:alternativelyyoucanexecutethewholeprocedureinonego.
4. Postfixpostfix/qmgr[6080]:warning:connecttotransportprivate/dovecot:Nosuchfileordirectory.
Reason:Ifyouhavetheaboveerror4,onereasoncouldbethatyouhaveenabledsaslauthforsmtpwithoutactuallyconfiguringsaslauth.Igot
thiserrorwiththefollowingrelevantdefaultentriesin/etc/postfix/main.cf:
smtpd_sasl_auth_enable=yes:tellPostfixtousesaslauth.
smtpd_sasl_type=dovecot:tellPostfixthatthesaslauthisdovecot.
smtpd_sasl_path=private/dovecotauth :tellPostfixwheretofinddovecotsaslauthandindeedthispathisreplicatedintheerror
message.
Solution:TellpostfixtoNOTusesaslauth:
1. shell> postconfe"smtpd_sasl_auth_enable=no
5.
TryingtouseGmailsMailFetchertocheckmailusingPOP3errors:
ServerdeniedPOP3accessforthegiveusernameandpassword.and
Serverreturnederror:"Plaintextauthenticationdisallowedonnonsecure(SSL/TLS)connections."
Reason:Dovecotdefaultdisablesplaintextauthenticationovernonsecureconnections.
Solution:ItwouldbebestifGmailMailFetchercouldworkoverasecureconnection(eg.POP3Sonport995),howeverIhavenotbeenableto
makethatwork.InsteadIsimplyconfigureDovecottoallowplaintextauthenticationalsoovernonsecureconnections:
1. emailservershell> nano/etc/dovecot/dovecot.conf:opentheDovecotmainconfigurationfileandaddthisrecord:
disable_plaintext_auth=no
2. Pressctrl+xandthenytocloseandsavethehostsfile.
3. emailservershell> /etc/init.d/dovecotstop&&sleep5&&/etc/init.d/dovecotstart:restartDovecotwaiting5secondsbetweenstopandstartto
bypasstheanvilchildprocessbuginDovecot2.0.13(andpossibleotherversionsaswell).
6. status=deferred(deliverytemporarilysuspended:connectto127.0.0.1[127.0.0.1]:10024:Connectionrefused)
7. NOQUEUE:reject:RCPTfromunknown[]:5545.7.1<targetemailaccount>:Relayaccessdeniedfrom=<>to=<targetemailaccount>
proto=ESMTPhelo=<FQDNsender>
Reason:LasttimemyAmavisdnewwasdown,Igotthe2above6&7errormessages.ConfirmthatAmavisdnewisdown:
shell> nmaplocalhost:ifyoudon'tseeport10024inuse,thenlikelyAmavisdnewisnotlistening.
shell> netstaptap:anotherwaytochecklisteningdaemons.
Solution1:RestartAmavisdnewandPostfix:
1. shell> /etc/init.d/amavisdnewrestart
2. shell> servicepostfixrestart
Solution2:Restartthemailserver
6. amavis(!)ClamAVclamdavscannerFAILED:run_averror:Toomanyretriestotalkto/var/run/clamav/clamd.ctl(Can'tconnecttoUNIXsocket
/var/run/clamav/clamd.ctl:Connectionrefused).
7. amavis(!!)WARN:allprimaryvirusscannersfailed,consideringbackups
Reason:Ifyouhavetheaboveerror6&7
Solution:
shell> psef|grepclam:testiftheclamdisrunning.
shell> /etc/init.d/clamavdaemonstart:starttheclamd.
1. 4504.7.1:Recipientaddressrejected:SPFResult=webmodelling.com:'SERVFAIL'erroronDNS'SPF'lookupof'webmodelling.com'(inreplyto
RCPTTOcommand))
Reason:
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
13/18
4/8/2015
UbuntuEmailServer
Solution:
Comments
Youcancommentwithoutloggingin
Register username
B U I S Helvetica
Captcha
Nickname
Facebook
Save Cancel
report reply 22Aug201319:58
hay..
it'sawesomeguideandijustfollowthisguidestepbystep,butihaveprobleminstepvirtualdomain..
uwil
aftercommand>>
Topics:1
Replies:6
outputwas>>
postmap:warning:connecttomysqlserver127.0.0.1:Accessdeniedforuser'mail_admin'@'localhost'todatabase'"postfix"'
postmap:fatal:tablemysql:/etc/postfix/mysqlvirtual_domains.cf:queryerror:Success
postmapqexample.commysql:/etc/postfix/mysqlvirtual_domains.cf
Usertype:Standard
Register:2013Feb22
so,canyouhelpme?whatisupposedtodo??
thanks
report reply 23Aug201311:18
Hiuwil
Rasmus
Myguessisthepasswordspecifiedformail_adminuserin/etc/dovecot/dovecotsql.confisnotidenticaltothe
passwordspecifiedforthemail_adminuserin/etc/postfix/mysqlvirtual_domains.cfornotidenticaltothepassword
specifiedforthemail_adminuserthenaddingmail_adminusertoMySql.
Usertype:Admin
Register:2012Dec21 Totestifthemail_adminusercanconnect,dothefollowing:
Topics:0
Replies:107
shell>mysqlumail_adminpMailAdminPassword:(thereisnospacebetweenpandMailAdminPassword).
Redothe"ConfigurePostfixforvirtualdomainsusingMySQL"sectionandpaycloseattentiontothepasswordeach
timeyouengagethemail_adminuser.
webfiddlerbynature
Anonymous
thankforreply.
Iguessin/etc/dovecot/dovecotsql.confisindentical,sameasin/etc/postfix/mysqlvirtual_domains.cf
andMySQLusertoo
/etc/postfix/mysqlvirtual_domains.cf
user=mail_admin
password=MailAdmin
dbname="Postfix"
query=SELECTdomainASvirtualFROMdomainsWHEREdomain='%s'
localhost=127.0.0.1
/etc/dovecot/dovecotsql.conf
driver=mysql
connect=host=127.0.0.1dbname=Postfixuser=mail_adminpassword=MailAdmin
default_pass_scheme=PLAIN
password_query=SELECTemailASuser,passwordFROMusersWHEREemail='%u'
mysql
mysql>CREATEDATABASEPostfix
mysql> GRANTSELECT,INSERT,UPDATE,DELETEONPostfix.*TO'mail_admin'@'localhost'IDENTIFIEDBY'MailAdmin';
GRANTSELECT,INSERT,UPDATE,DELETEONPostfix.*TO'mail_admin'@'localhost.localdomain'IDENTIFIEDBY'MailAdmin';
please,correctmeifi'mwrong,islooksdifferent?
iusingubuntu12.04
thankyou
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
14/18
4/8/2015
UbuntuEmailServer
Yourconfigurationlookscorrect,howeveryoudidnotwritewhetheryouhadtriedtomanually
connecttothePostfixdatabaseandifyoudidwhetheryoucouldconnectornot:
shell>mysqlumail_adminpMailAdminPassword
Rasmus
Usertype:Admin
Register:2012Dec21
Topics:0
Replies:107
webfiddlerbynature
Usertype:Standard
outputcommand
Register:2013Feb22 mysql>
Topics:1
Replies:6
anythingelse?igetstuckinthispart:(
canyouhelpme,please
in/etc/postfix/mysqlvirtual_domains.cfijustremoved""indbname.
Usertype:Standard
Register:2013Feb22
Topics:1
Replies:6
/etc/postfix/mysqlvirtual_domains.cf
user=mail_admin
password=MailAdmin
dbname=Postfix
query=SELECTdomainASvirtualFROMdomainsWHEREdomain='%s'
localhost=127.0.0.1
postmapqexample.commysql:/etc/postfix/mysqlvirtual_domains.cf
outputcommand>>
example.com
itsworkingnow
thankyou:)
report reply 24Aug201318:03
hirasmus
ihaveanotherissueagain..*sign*
uwil
afterinputcommand>>
Usertype:Standard
Register:2013Feb22 lsl/home/vmail/examples.com/uwil/Maildir/new
Topics:1
Replies:6
outputwas>>
ls:cannotaccess/home/vmail/example.com/uwil/Maildir/new:Nosuchfileordirectory
iguessmail_locationwasrightin/etc/dovecot/dovecot.conf
and,whenitriedtelnetlocalhostimap
shell>telnetlocalhostimap
Trying127.0.0.1...
Connectedtolocalhost.
Escapecharacteris'^]'.
*OKWaitingforauthenticationprocesstorespond..
*BYEDisconnectedforinactivity.
Connectionclosedbyforeignhost.
canyouhelpmeagain??plz
thankyou:)
Reconfirmthat:
1. /etc/dovecot/dovecot.confcontainsthecorrectmail_location:mail_location=
maildir:/home/vmail/%d/%n/Maildir
2. /etc/postfix/main.cfcontainsthecorrectvirtualtransport:virtual_transport=dovecot
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
15/18
4/8/2015
UbuntuEmailServer
2. /etc/postfix/main.cfcontainsthecorrectvirtualtransport:virtual_transport=dovecot
3. /etc/postfix/master.cfregisterthedovecotlda:dovecotunixnnpipeflags=DRhuuser=vmail:vmail
argv=/usr/lib/dovecot/deliverf${sender}d${recipient}
4. Thatnoemailiswrittento/home/uwil/Maildir/new:ifthereisanemailthereafteryouusedtelnettosendan
emailthroughPostfixtouwil@example.com,dovecotldawillsendemailtosystemaccountsinsteadvirtual
accounts.
5. Remembertorestartdovecot&postfixaftermakingchanges:
1. shell>etc/init.d/dovecotstop&&sleep5&&/etc/init.d/dovecotstart
2. shell>servicepostfixrestart
Youwillneedtoseeanemailin/home/vmail/example.com/uwil/Maildir/newbeforeitgivesmeaningtocontinue
withshell>telnetlocalhostimap
webfiddlerbynature
uwil
Usertype:Standard
Register:2013Feb22
Topics:1
Replies:6
webfiddlerbynature
NotethoughthatgmailisnotgoodfortestingbecausegmailwillrefuseemailsifitcannotconfirmtheIPaddressof
Usertype:Admin
Register:2012Dec21 thesendingdomain(calledreverselookuporrDNS),eg.ifyousendfromexample.comonyourlocalmachine,
thengmailwilllookupexample.comandreceiveanIPdifferentfromtheIPyouaresendingfrom.
Topics:0
Replies:107
webfiddlerbynature
uwil
Usertype:Standard
Register:2013Feb22 so,whatisupposedtodo,togetmaketestingiftheSASLTLSworkinginmymailserverasrelayingemail
Topics:1
Replies:6
likeyourtutorial.ihaveonlyaccountsgmailfortherealemail,andidon'thavedomainlike
'webmodelling.com'asyou.
canyouadviceme?
report reply 29Aug201305:42
Hiuwil
Ihavecreatedanemailaddressforyou:uwil@webmodelling.com,youcanaccessyouremail
onlineatwebmail.webmodelling.comusinguwil@webmodelling.comforusernameandthe
passwordIhavePM'edyou.
Rasmus
Usertype:Admin
Register:2012Dec21
Topics:0
Replies:107
webfiddlerbynature
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
16/18
4/8/2015
UbuntuEmailServer
thankyousomuchforeverythingyourhelp..i'msopleasure
Anonymous
ihavetriedtorelayingemailfrommymailservertouwil@webmodelling.com,butit's
working.myinboxinuwil@webmodellingkeepsempty..juststuckinhere:(
canhelpmeagain?
thank
report reply 29Aug201311:36
Hiuwil
Inthe"SASLtestitworks"thereare3tests.Tellmeexactlywhatpartsofthe
testsyoucanpassandwhatyoucannotpass.
Rasmus
Usertype:Admin
Register:2012Dec21
Topics:0
Replies:107
webfiddlerbynature
uwil
buticannotrecievethatemai..inboxstillempty..
Usertype:Standard
Register:2013Feb22
Topics:1
Replies:6
beforethatiguessihavepassedtheAUTHPLAIN,andsuccess..
Rasmus
Usertype:Admin
Register:2012Dec21
Topics:0
Replies:107
Ifyoupassed"SASLTestitworks"test3.3.3"2352.7.0
Authenticationsuccessful",thenSASLshouldactuallywork
andlikelysomethingelseisprohibitingyoufromsending
mail.
Youshouldlookinthelogfiles:/var/log/mail.log&
/var/log/mail.err.JustaftertryingoutSASLtest3,youshould
dothefollowing:
shell>tail50/var/log/mail.log:printthelast50
recordsofmail.logtoscreen.
shell>tail50/var/log/mail.err
shell>mailq:seeifsomethingispendinginthemail
queue.
Hopefullyyouwillbeabletogetahintfromtheabove.
webfiddlerbynature
Mostdownloaded
C#UtilityFunctions
FlexCaptcha
QueryString
Popularread
ISPConfigsetup
InstallOracleonSolaris
UbuntuVirtualization
Bacula
webfiddlerbynature
FavouriteProjects
findthaifurniture.com
favouritebaker.com
menulab.com
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
17/18
4/8/2015
UbuntuEmailServer
http://webmodelling.com/webbits/ubuntu/ubuntuemailserver.aspx#ubuntumailserverbasictest
18/18