Search code examples
scalasmtpjakarta-mail

How to use SMTP server in scala to send emails


i wrote this function to send emails with 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)
      }

but when i run my code, i get the following error:

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

Does anyone have any idea what this mean ?


Solution

  • You're missing the implementation classes of the javax.mail API. Could you include

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

    in your build.sbt. The version number should match the entry of "javax.mail" % "javax.mail-api"