虽然不是直接的答案,但它展示了如何设置 javax.mail
的属性。这种方法非常简单,因为您不需要使用 Play 插件来解决此问题,当可能时,我总是选择简单和少基础架构的方案。
首先,在您的build.sbt
中包含它。
"javax.mail" % "mail" % "1.4.5"
import javax.mail._
import javax.mail.internet._
对于你需要的任何参数,请使用标准Play配置系统
private val host = config.getOptional[String]("smtp.host").getOrElse("localhost")
private val port = config.getOptional[String]("smtp.port").getOrElse("25")
private val account = config.getOptional[String]("smtp.account").getOrElse("not configured")
一旦您从配置中获取了邮件属性,请设置它们...
val props = System.getProperties
props.setProperty("mail.smtp.host", host)
props.setProperty("mail.smtp.port", port)
props.setProperty("mail.smtp.auth", "true")
props.setProperty("mail.smtp.starttls.enable", "true")
设置您的身份验证...
val auth = new Authenticator() {
override def getPasswordAuthentication: PasswordAuthentication = {
new PasswordAuthentication(account, passwd)
}
}
def send(toAddress: String, subject: String, htmlBody: String): Unit = {
val session = Session.getInstance(props, auth)
val msg = new MimeMessage(session)
msg.setFrom(new InternetAddress(account, "Someone"))
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress))
msg.setSubject(subject)
msg.setSentDate(new Date())
val multiPart = new MimeMultipart("related")
val htmlBodyPart = new MimeBodyPart()
htmlBodyPart.setContent(htmlBody, "text/html")
multiPart.addBodyPart(htmlBodyPart)
msg.setContent(multiPart)
Logger.info(s"Sending '$subject' to $toAddress")
Transport.send(msg)
}
应该可以了。考虑到可能会抛出异常,你应该将整个内容都包裹在Try
monad中。此外,如果你需要发送附件,邮件已经是多部分消息了,你只需要添加更多的部分到html消息中即可。
可能没有这样的可能性。以下是SMTPMailer的实现:
private lazy val instance = {
if (smtpConfiguration.mock) {
new MockMailer()
} else {
new CommonsMailer(smtpConfiguration) {
override def send(email: MultiPartEmail): String = email.send()
override def createMultiPartEmail(): MultiPartEmail = new MultiPartEmail()
override def createHtmlEmail(): HtmlEmail = new HtmlEmail()
}
}
}
属性被设置在更深的email.send()中,它使用了apache的commons-email。唯一设置这些属性的方法是将这些属性设置为系统属性,因为它们稍后会被使用:
final Properties properties = new Properties(System.getProperties());
但是它们稍后可能会被覆盖,因为在下一行中有一些属性被设置:
properties.setProperty(MAIL_PORT, this.smtpPort);