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

标签 scala email mail-server

我计划使用 Scala 和 Akka 构建一个将严重依赖电子邮件的服务。事实上,与我的服务的大部分沟通都是通过向它发送信件并获得回复来完成的。我想这意味着我需要一个可靠的电子邮件服务器以及从 Scala 与它通信的方法。

问题是,这样做的最佳实践是什么?我应该选择哪个电子邮件服务器以及有哪些 Scala 解决方案来完成此任务?

最佳答案

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

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.")
      }
    }
  }
}

许多 web 框架会为您实现方便的方法来处理 mime 类型、附件等。

不用说,发送电子邮件永远不会 100% 可靠。这更像是一劳永逸的操作。默认情况下,邮件协议(protocol)中没有确认或错误传播,这通常被正常接受。

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

关于scala - 使用 Scala 接收和发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22282398/

相关文章:

css - 使用内联 CSS 的 GMail 电子邮件中的水印 - 无法使用 STYLE 标签 - 在电子邮件正文中心覆盖透明图像

email - 电子邮件中的不同内容类型

dns - 如何为邮件服务器设置PTR记录? (Bind9 和 Webmin)

scala - Scala 中带有 getOrElse bool 默认值的选项

scala - 你能在 Scala 中部分绑定(bind)一个 0 元函数吗?

list - 单个列表中的字符串连接

centos6 - 合并两个 dovecot Maildirs

scala - 用于生成图中所有拓扑排序的尾递归算法

Ruby Net::SMTP - 使用密件抄送发送电子邮件:收件人

web-services - 如何通过 Web 应用程序与邮件服务器通信