deliver electronic mail with scala from the future
Via the copy and paste method
resolvers += "dka-oss-maven" at "https://dl.bintray.com/dka/oss"
libraryDependencies += "dka" %% "courier" % "0.2.1"
Note. If you are a bintray-sbt user you can optionally specify the resolver as
resolvers += bintray.Opts.resolver.repo("dka", "oss")
deliver electronic mail via gmail
import courier._, Defaults._
val mailer = Mailer("smtp.gmail.com", 587)
.auth(true)
.as("[email protected]", "p@$$w3rd")
.startTls(true)()
mailer(Envelope.from("you" `@` "gmail.com")
.to("mom" `@` "gmail.com")
.cc("dad" `@` "gmail.com")
.subject("miss you")
.content(Text("hi mom"))).onSuccess {
case _ => println("message delivered")
}
mailer(Envelope.from("you" `@` "work.com")
.to("boss" `@` "work.com")
.subject("tps report")
.content(Multipart()
.attach(new java.io.File("tps.xls"))
.html("<html><body><h1>IT'S IMPORTANT</h1></body></html>")))
.onSuccess {
case _ => println("delivered report")
}
If using SSL/TLS instead of STARTTLS, substitute .startTls(true)
with .ssl(true)
when setting up the Mailer
.
Since courier is based on JavaMail, you can use Mock JavaMail to execute your tests. Simply add the following to your build.sbt
:
libraryDependencies += "org.jvnet.mock-javamail" % "mock-javamail" % "1.9" % "test"
Having this in your test dependencies will automatically enable Mock JavaMail during tests. You can then test for email sends, etc.
import courier._
import org.specs2.mutable.Specification
import scala.concurrent.duration._
// Need NoTimeConversions to prevent conflict with scala.concurrent.duration._
class MailSpec extends Specification with NoTimeConversions {
"the mailer" should {
"send an email" in {
val mailer = Mailer("localhost", 25)
val future = mailer(Envelope.from("[email protected]")
.to("[email protected]")
.cc("[email protected]")
.subject("miss you")
.content(Text("hi mom")))
Await.ready(future, 5.seconds)
val momsInbox = Mailbox.get("[email protected]")
momsInbox.size === 1
val momsMsg = momsInbox.get(0)
momsMsg.getContent === "hi mom"
momsMsg.getSubject === "miss you"
}
}
}
}
Here is an excellent article on using Mock JavaMail.
Original work by Doug Tangren (@softprops) 2013