To provide an “Email Sending ” functionality in your Play App that is being built with Play 2.2.1, follow these steps ( this post summarizes the work done step by step).
1) Add following dependency in build.sbt (or in Build.scala for Play 2.1.x or older versions)
“com.typesafe” %% “play-plugins-mailer” % “2.1-RC2”
2) Add following lines to “conf/application.conf” file
smtp.host=smtp.gmail.com smtp.port=587 smtp.ssl=true smtp.user="abc......@gmail.com" <-- your email id within double quotes smtp.password=yourpassword <-- without double qoutes
3) Create a new File in conf folder with name “play.plugins” and add following line into it
1500:com.typesafe.plugin.CommonsMailerPlugin
4) Delete all the code in “Application.scala” and write following code to it
package controllers import com.typesafe.plugin._ import play.api._ import play.api.Play.current import play.api.data._ import play.api.data.Forms._ import play.api.mvc._ object Application extends Controller { case class MailData(email: String) val mailForm = Form( mapping( "email" -> email)(MailData.apply)(MailData.unapply)) def index = Action { Ok(views.html.index(mailForm)) } def sendMail: Action[play.api.mvc.AnyContent] = Action { implicit request => mailForm.bindFromRequest.fold ( formWithErrors => { Redirect("/") }, mailData => { val mail = use[MailerPlugin].email mail.setSubject("Email sent using Scala") mail.addRecipient(mailData.email) mail.addFrom(mailData.email) mail.send("Hello World") Redirect("/") }) } }
5) Delete the code written in views/index.scala.html and write the following code to it
@(mailForm: Form[controllers.Application.MailData]) @import helper._ @main("Email Sending App") { @helper.form(action = routes.Application.sendMail, 'id -> "MailForm") { @inputText(mailForm("email"), '_label -> "Email") <div class="form-actions"> <input type="submit" class="btn btn-primary" value="Send Mail"> </div> } }
Note – For a Demo you can download the Demo App from
https://github.com/gupta-himanshu/himstein/tree/master/mailSendingApp
Filed under: Scala, Web Tagged: Eclipse, Play framework, sbt, scala
