10

Adding an Email sending functionality in Play using Scala

 3 years ago
source link: https://blog.knoldus.com/adding-email-sending-functionality-play-scala/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Adding an Email sending functionality in Play using Scala

Reading Time: < 1 minute

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

xxxxxxxxxx
smtp.host=smtp.gmail.com
smtp.port=587
smtp.ssl=true
smtp.user="[email protected]" <-- 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

xxxxxxxxxx
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

xxxxxxxxxx
@(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>
}
}

These are the steps to add Email sending functionality in Play using Scala.

Note – For a Demo you can download the Demo App from

https://github.com/gupta-himanshu/himstein/tree/master/mailSendingApp


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK