使用Scala接收和发送电子邮件

src*_*091 15 email scala mail-server

我打算使用Scala和Akka构建一个服务,它将严重依赖于电子邮件.事实上,与我的服务进行的大多数沟通都将通过发送信件并获得回复来完成.我想这意味着我需要一个可靠的电子邮件服务器以及与Scala通信的方式.

问题是,这样做的最佳做法是什么?我应该选择哪种电子邮件服务器以及用于完成此任务的Scala解决方案?

yǝs*_*ǝla 15

通常使用JavaMail API.在您的项目中,您可以将其包装在您自己的Scala库中或使用现有库.以下是在Lift框架中使用现有API 的示例Mailer:

package code
package config

import javax.mail.{Authenticator, PasswordAuthentication}
import javax.mail.internet.MimeMessage

import net.liftweb._
import common._
import util._

/*
* A Mailer config object that uses Props and auto configures for gmail
* if detected.
*/
object SmtpMailer extends Loggable {
  def init(): Unit = {

    var isAuth = Props.get("mail.smtp.auth", "false").toBoolean

    Mailer.customProperties = Props.get("mail.smtp.host", "localhost") match {
      case "smtp.gmail.com" => // auto configure for gmail
        isAuth = true
        Map(
          "mail.smtp.host" -> "smtp.gmail.com",
          "mail.smtp.port" -> "587",
          "mail.smtp.auth" -> "true",
          "mail.smtp.starttls.enable" -> "true"
        )
      case h => Map(
        "mail.smtp.host" -> h,
        "mail.smtp.port" -> Props.get("mail.smtp.port", "25"),
        "mail.smtp.auth" -> isAuth.toString
      )
    }

    //Mailer.devModeSend.default.set((m : MimeMessage) => logger.info("Sending Mime Message: "+m))

    if (isAuth) {
      (Props.get("mail.smtp.user"), Props.get("mail.smtp.pass")) match {
        case (Full(username), Full(password)) =>
          logger.info("Smtp user: %s".format(username))
          logger.info("Smtp password length: %s".format(password.length))
          Mailer.authenticator = Full(new Authenticator() {
            override def getPasswordAuthentication = new
              PasswordAuthentication(username, password)
          })
          logger.info("SmtpMailer inited")
        case _ => logger.error("Username/password not supplied for Mailer.")
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

许多Web框架将为您处理mime类型,附件等实现方便的方法.

毋庸置疑,发送电子邮件永远不会100%可靠.它更像是火和忘记操作.默认情况下,邮件协议中没有确认或错误传播,这通常被认为是正常的.

如果您使用SMTP邮件发件人,您可以将其连接到任何邮件服务器,无论是外部邮件服务器,如gmail,还是本地安装的postfix.


Tva*_*roh 6

您可以尝试使用callier,这是Java Mail上的Scala层,可以提供更流畅的API.不幸的是,目前在JVM上没有用于电子邮件发送的非阻塞解决方案(如果我错了,请纠正我).

  • 这不会使它成为非阻塞,只是异步.请参阅http://stackoverflow.com/questions/2625493/asynchronous-vs-non-blocking或http://doc.akka.io/docs/akka/snapshot/general/terminology.html从这个角度来看,信使是异步的. (4认同)