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

时间:2017-05-26 10:06:06

标签: scala smtp javamail

我写了这个函数来发送带有java邮件的电子邮件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$1(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$1$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

有谁知道这是什么意思?

1 个答案:

答案 0 :(得分:2)

您错过了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"

的条目匹配