如何在 Play-Mailer 中设置 JavaMail 属性

How to set JavaMail properties in Play-Mailer

我想知道如何设置 JavaMail 属性,例如:

mail.mime.address.strict

Play-Mailer 插件中。

应该没有这种可能吧。下面有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);

不是直接的答案,但它确实展示了如何设置原始 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 消息中添加更多部分