play for scala 通过网易smtp发送邮件

最近用play来做一个小项目,里面用到了发送邮件的功能。这里我将这部分抽出来分享,毕竟目前来看paly于scala方面的中文资料在网上还是毕竟少,希望我的这篇文章能为有需要的人提供一点思路。

下面写下我发送邮件的配置以及步骤,我用的是网易yeah.net邮箱,需要在邮箱设置里面启用smtp和设置客户端授权码才行。

我们在play应用中的build.sbt中引入相应的包

"com.typesafe.play" %% "play-mailer" % "5.0.0"

然后在application.conf文件中配置smtp服务地址和账号密码

play.mailer {
  host = "smtp.yeah.net"
  user = "用户名"
  password = "客户端授权码"
}

需要注意的是用户名不要带后缀,比如你的邮箱是xxx@yeah.net,那么用户名就是xxx

编写Mail.scala

import javax.inject.{Inject, Singleton}
import play.api.libs.mailer._

@Singleton
class Mail @Inject()(mailerClient: MailerClient) {
  def sendEmail: Unit = {
    val email = Email(
      "Simple email",
      "Service <username@yeah.net>",
      Seq("xxxx <xxxx@qq.com>"),
      attachments = Seq(),
      bodyText = Some("A text message"),
      bodyHtml = Some(s"""<html><body><h1>Hello, Play for Scala</h1></body></html>""")
    )
    mailerClient.send(email)
  }
}

最后在需要发送邮件的地方实例化Mail调用sendEmail函数就可以了。

 

原创文章,转载请注明出处。

posted on 2016-11-20 21:57  唐际忠  阅读(716)  评论(0编辑  收藏  举报