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

Spring Java Mail

Explains how we can use Spring framework mail API

Uploaded by

suryavamsi8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
85 views

Spring Java Mail

Explains how we can use Spring framework mail API

Uploaded by

suryavamsi8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
CodesENe) Home Java SE Jaa EE bes Servers coaing Videos Free Java Tutorial Videos (11.8 Ke Programmers Joined) Wo rospactyourprivaey ‘The Java Spring Tutorial Spring Framework 4 Tutorial Leam Spring Boot Spring In Action Spring n Practice Pro Spring 3 Spring Integration in Action Spring Batch in Action Spring Web Services 2 Cookbook Spring Recipes: A Problom Solution Approach Spring Framework: A Step by Step Approach for Leaming Spring Framework Developing Enterprise (Soares ‘Applications with Spring: An End-to-End Approach Just Spring Spring Data Spring Persistence with Hibernate (Beginning) Pro Spring Security Pro Spring MVC: With Web Flow Latest Spring projects Spring Framework 4.2.5 GA Spring Framework 32.16 GA Spring AMP 1.5.5 Spring for Android 1.0.1 Spring Balch 3.0.7 RELEASE Spring Data JPA 19A.RELEASE Spring Data Apache Hadooo 22.4.G8, Spring Data REST 25.1 Spring Data Reds 1.7.1 Spring Data MongoD8 19, RELEASE Spring Data Neos} 44... RELEASE Spring Data Gemfre 1.8.1 Spring Integration 42.5, Spring Moble 1.1.4 Spring Roo 1.3.0 Spring Securty 4.0.4.RELEASE Spring Socal Core 1.1.4 Spring Socal Facebook 2.0.3 Spring Socal Twitter 1.1.0 Spring Social Linkedin 1.0.0.6, Spring Web Flow 2.4.2 Spring Web Services 2.8.0 Spring X13. Popular Spring Downloads Spring Framework 42.5 RELEASE Spring Framework 3:26 RELEASE Spring Toa Suite 5.73 RELEASE Spring GroavyGrails Tool Suite 3.64. RELEASE tape 260628 Sending e-mail with Spring MVC Last Updated on 20 January 2016 | Print Email ‘The Complete Java Developer Course. Learn Step by Step “Table of contents 1.Spring framework’ support for emai 2.Reauied jar fos 3.Creatng e-mail sending form 4.Contguing SMTP server setngs and Spring MVC ‘.Creatng Spring MVC contrllar class 6.Creatng result page and eror page 7.Run the apptction ‘8.Download Eclipse projeclWAR fle This tutorial provides a sample spring MVC application that alows user sending an e-mail message by filing a web form. The e-mal form looks tke folowing sereensnot m Sending e-mail with Spring MVC Te Subject In ths tutorial, you are supposed ta familar wih Java EE development as well as developing Spring MVC-based applestions. 1. Spring framework’s support for e-mail Based on Javatol, Spring framework provides highevelabsiraction API which realy simiies e-mail sending proces. Let’ take abi look at ths AP nthe following class lasram “To send e-mail messages, wo can use an implementation of interlace Ma 2Sendar ~ the JavatlatSendestepl class hich s but upon on JavaMal I's convenient to configure ths implementation as a bean in Springs context ean a naiSenger” classe"org.springtranework.rail.jovenail.JovaNalTSenderingI°> 2 she settings. ==> 3) fort value="sHhpoaT” “property haner"passuors value=" PRSSRORD™ /> 5 Tice acdieional properties speci#ic to Jevataid 2 ‘props " “prop keys'natt. transport pratocot"ssntpe/prep> 2 “prop eyainais_shep-authStruee/ prep a “prop kepovnaiionep.startelsvenable™>€°uec/prop> a recaps 1S cipropertye 16 cfoean “This bean holds properties for SMTP and JavaMail and can be inj send an e-mal for example: to a businasslservce class which needs to 1) mailsendersendenil)s In which ona: isan object ofa type thal implements ai vecsace interface, such as SisptevastNessage cass, We can construct the ena: object as fotows ‘Sinplevat message enail = new Sinplo¥atNessag6()5 fern setTo(totdaress)? feral setsubyect(subject): frat setText (6009); “Thats fora simple mail message (plain tox!) In caso if we want to Sond HTML e-mail or attach fos o tho e-mail, we can use wnovaiiMacazgo class wth the help of Winavocoaqerreparator dass and MincMoasageHelper dass. For ‘example, sending an e-mallin HTML format wth an attachment: naLisenger.sen(neu MinatessagePreparator() { public void prepare(hinetessage ninehessage) throws Messagingexception ( inetessagerel per ressage. = new RinePassagerelper(mineressagey true, “UIF-8")5 hedsoge.setFron(sconcnatl); hessoge setTo(toenall): hessoge.setsubject(°A Tile for you"); Message setText(schosee the attacherc/to", teve) essage adahttacnnent(*coolstutts coc", mew File(-Coolstut#.doc*)); ) Lay “The folowing table summarizes the interfaces and classes provided In ox. springtzanenork.mat2 package [Deaiatisendecrepl | mnwarimescase | Click on @ fnkin the tablet see API documentation fo The corespanding iterfacelciass, 2. Required jar files “The application requires the fotowing jar files copied to ts wes=rwe\in directory: Raqured arf aan peut ‘Spring rarvowork ‘Roache Commons Lagging NOTE: cick on a hyperink inthe table above to download the corresponding sofware, “The sample application we are going o bull contains the following key fles: eat foen.se0: displays an e-mail frm sown. en Shows successful message afer the e-mail has been sent -eror. jee: ShOWS erTor message in case ofan exception Is thrown. Seo icorto3:er, ava the Spring controller class that takes Input from e-mal form, calls Spring's rausendor (9 tand the e-mail, and edicts user to ether success page or eror page + seringerve nt: Spring's context configuration fl. Here we vill covigure SMTP server settings and various properties for JavaMail ‘+ sam: Web deployment descrpter le. 3. Creating e-mail sending form Create a JSP fle called nnas1zcen. sep wit the folowing HTML code: 1) eK@ pane Languoges"Java” contentTope-"cext/htnl; charset-UTF-#™ 2 OS fagecacodingsutF-a-a> 5 caooet¥eehent PUBLIC *-//Wc//07D wm 4.01 Transttional/ EN” a SHRED! nw ong/ TRUER /Doose. ded"> neta heto-equive"Content-Typa" contente"text/tel;,charset-UTF-B"> iestsit with Spring mCC/eseie> 5 Lineas> 38 Stoays enters 2 ‘hbbSending e-nati with Speéng MYCIN Fs st actdonesengenail co"? ie fret widths ie ‘ceastase/ a> i Skabcinput typee"soxt” nanee"recipsons sizen"6s" /oe/ta> % eres 2% ctepsubjecti a eeabeinput typescoxt” nanee"subject™ stzesr6s" /oertd> 2 ees 2 ctapmessagescita> Es ‘Gibctentaren cols="52" rows="30" nanestnessage"> is ee > “input typen"svanits values"Sene E-nasl” /> se creas z recs 3 ytabies 3 Me) cpeenters 23 bean idernaiiSender” elasse"org,springfrancwork.natl. javanotl. J3vaasISenderinpI"> Sntg.gnoll-con” > property ranem"por” valles'587" 7> “property rane~"wserrana”waloee"yourenail” f> password” values"yourpassword” [> Javatal properties» “prep key="naiL. transport, protocol">smtpe/erap> ‘prop keys'nailsntp.auth'ptruee/rop> “prop keyevnail seep. svarttlecenapleestruee/prop> “ives bean ide"yienesolver ‘Classe org springtrateyork. web, servlet. view.2nternalResourceviewResolver"> “property tance previe™ hs ‘property rane suffix" C80" ‘Classe"org. springfranework.web, servlet handler. SinpleMappingExcepttonResolver"> “property tance" except lonmappings”> ‘prop . cbt Keyra Langs Exception ero prop> “This configuration ie ratystraightforwar :10l6 Spring o scan the package net. codejava.sering fr inlialzing comparents which are annotaed by Spring annotation (t's a Spring controler class, in case ofthis application), Bean ws 1sender* tis isthe important part because it declares a Spring bean for e-mailimplamentation — the Java ISence= inp! ase and configures SMTP server settings, which for a Gmail accaunt in ths as. ‘This boan wil be injected to @ Spring contra class which wil be covered inthe next section Bean vieuresciver: maps logical vow names to real SP fie names, Bean sinsieverpingixcoptsonkeac=ver: maps all exceptions of ype java.teng.txception to be handled by Breor ssp page “The web deployment descriptor le (uct. xn) fs configured as flows: “2am versione1.0% encodsng="UIF-8°2> “oa-app ating xst=*netps/ eww org/2881/2LSchena-Anstance™ mish ps1 avasun. confers Jovae ninasebarhtt ps) Java, sun-con/aal as Savaee/Meb-app_2_S.x8d° sSLlsenenabocation="heép! save. sun. coe/ ana Retpe//jovs-sin.conpenl si javsce/ueb. SP. tacrssnpp. 10" versions"2 0" ‘alsplay-nanasCaallspringnvcc/display-nare> “servlet-nane>spetngcontrolier /serviet-rane> ‘Servlet-classvong.springéancwore. web, servlet. DispatcherServlet “punan-hane>contextConfiglocationé/paran-nane> ‘Sfarancvalucs MES“ IN®/Speing-nve, en c/oaran. value) essoiteparans Ehedasoneseareupssc/oad-on-startup> eiserviet> servlet -napping> “servletsrane>speingcontroller Sirlipateern*sdocyurtopattern> cistviet napping? swelcome-file-2ist> “welcane-(siestnmasTForn. jape/ueleone-file> sjueicona-Filesiise> cpus 365> It doclares Spring controler servot with its contest configuration Mle |/azi~2n2/apring-nve.xmi). The controler is confgured to handle all requests whose URL end with pattem: “do. And the default page when accessing the applestion is he email frm (tai orn. 4er) ‘This vdeo tutorial: The Java Spring Tutorial holp you dscover how to mastr the Spring framework instant. 5. Creating Spring MVC controller class Im order to handle suomission from the e-mail form, we need to create a Spring controler class as foo: pack 6 net code java. springs Javan. servlet nttp.fetgservietRequest Inport org. springtranevork beans. factory amnetation.Autowireds tport org. springtranework nail: Sinpienaiinersape) {port orfspeingeranework aad. javonall-Jwvotat Senders Inport org. springtranework stereotype. coverolien: {nport ora. springfranework web, ind-snnavaeion-Requestoppings Inport org. apringrranexorkoeb.indcannotation.nequestethody 18 gontrotier Ti piequesemapping("/sendinast. co") 12 publi class Sendenalicontraller ( 12) autores 8] anaueseringintat = teqeptetes 07) 2] SMe ennaetet tenets to see) ¢ BR) Sen rete, eerste BSUHESRGI SESS Sty) BY etre aE En, reciteeates) BE) Bamoreernant., setaaaee 38 ‘enail = new SinpleMatIMessage(); 3 mismmccems 3) SUSE 36 ‘ral Sender 39 return "Result" Bo a5 “This controler clas is quite simple. tis declared as a Spring MVC controler by the annotation tcontral Ler, ands ‘mapped tothe e-mail form's action by the @Recuestapoing annotation, We inject the =aiiSendes bean declared in soringenvo.am! fle int th controle through the private feld also ramed mai.1sendex. The injection is done automaticaly by Spring as we use the eaten: ea annotation “The method Josensina:: (y's responsible for capturing input from e-mail form, cr and sending the &-mall by invoking the cons) method on the naisancier bean. The e-mails in plaintext format. find and lead appropriate ing a Sizptetia::Hessase object Finally, returns a view named “Resul which causes Spring to use the» cxitoaow ISP fle (aeour.j20). 6. Creating result page and error page Code the sone. jap Me as folows: 1] ei page 1anguagen"$ava" contentTypes"text/henl; charset-UTF-8" 2) pageencoding- uit 3) caooli¥ee ent FueL1e *-//42c//010 HIM. 4,61 Transttionat//EN™ 2 peep wun org/Ta/nenla/ loose, > ; “content-Type" contente"text/htals charset-UTF-8"> 8) Gielessend ecnoil resulte/tities 5) Geass a eter 2 hzsThank you, your enail has been sents BB) reenter Xe) cpap 15 Sen ‘And code te Eeroz.3ep a8 flows <10oGi¥ec herd PUBLIC *-//WC//07D WML 4,01 Teansttsonat//EN™ “Sheps / aw. oFg/TA/henLA/ Loose. stds ‘neta hetp-equive"content-Type” content="text/heml; charset-UTF-°> Citleserrorestitie> ‘iheaes 28 Soap, 2 SeTESorry, the email was not sent becouse of the following errers 8 eh einen nessa) > 15 crooay> 36) nem ‘As we can see, the result page simply tolls the user thatthe e-mailhas been sent, while the exror page dsplays an error massage f any exception thrown dung the process of sending e-mail 7. Run the application So far we have created al the key pieces ofthe appation, Let's deply ton a serlt container tke Tomcat, and access the appization by typing the follwing URL into browsers adress bar (your host name and port number maybe diferent, depending on sorver configuration) nip Mocatnos 8080/EmalSpeing MVC “The e-mail form i plyes, type in required information: = eS © [DB tocathoss8000/EmaiSocnowve 2/0 = Sending e-mail with Spring MVC To: [osbmameredkna Sabjce [Quesion ab Spina VE ri Mewaae i Secsaae Woe Hit Sond E-mail buton, may take @ whe forthe e-mail to be sant. A suocessful message comes from the result page in case everything i going wo: io 0 a Thank you, your email has been sent. In case of eror (such as network failure or the SMTP server could not be reached), the error page displays:

You might also like