如何在scala中使用SMTP服务器发送邮件

How to use SMTP server in scala to send emails

我写了这个函数来发送电子邮件 java mail Api:

def createMessage: Message = {
        val properties = new Properties()
        properties.put("mail.transport.protocol", "smtp")
        properties.put("mail.smtp.host", "smtp.gmail.com")// smtp.gmail.com?
        properties.put("mail.smtp.port", "25")
        properties.put("mail.smtp.auth", "true");
        val authenticator = new Authenticator() {
          override def getPasswordAuthentication = new
              PasswordAuthentication(username,password)
        }
        val session = Session.getDefaultInstance(properties, authenticator)
        return new MimeMessage(session)
      }

但是当我 运行 我的代码时,我得到以下错误:

Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
    at javax.mail.Session.initLogger(Session.java:221)
    at javax.mail.Session.<init>(Session.java:206)
    at javax.mail.Session.getDefaultInstance(Session.java:316)
    at test.MailAgent.createMessage(MailAgent.scala:43)
    at test.MailAgent.<init>(MailAgent.scala:20)
    at test.test$.delayedEndpoint$test$test(test.scala:9)
    at test.test$delayedInit$body.apply(test.scala:8)
    at scala.Function0.apply$mcV$sp(Function0.scala:34)
    at scala.Function0.apply$mcV$sp$(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App.$anonfun$main$adapted(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:389)
    at scala.App.main(App.scala:76)
    at scala.App.main$(App.scala:74)
    at test.test$.main(test.scala:8)
    at test.test.main(test.scala)
Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 16 more

有人知道这是什么意思吗?

您缺少 javax.mail API 的实现 类。你能包括

// https://mvnrepository.com/artifact/com.sun.mail/javax.mail
libraryDependencies += "com.sun.mail" % "javax.mail" % "1.5.6"

在你的 build.sbt 中。版本号应与 "javax.mail" % "javax.mail-api"

的条目匹配