gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:37:35 24 4
gpt4 key购买 nike

我计划使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com