Adding an “Email sending” functionality in Play using Scala


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

Advertisements
This entry was posted in Scala, Web and tagged , , , . Bookmark the permalink.

One Response to Adding an “Email sending” functionality in Play using Scala

  1. Pingback: A Non-blocking “Email sending” functionality in Scala | Knoldus

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s