scala-news-reader

rss/atom news reader in scala

git clone https://9o.is/git/scala-news-reader.git

SmtpMailer.scala

(2050B)


      1 package com.joereader
      2 package config
      3 
      4 import javax.mail.{Authenticator, PasswordAuthentication}
      5 import javax.mail.internet.MimeMessage
      6 
      7 import net.liftweb._
      8 import common._
      9 import util._
     10 
     11 /*
     12  * A Mailer config object that uses Props and auto configures for gmail
     13  * if detected
     14  */
     15 object SmtpMailer extends Loggable {
     16   def init(): Unit = {
     17 
     18     var isAuth = Props.get("mail.smtp.auth", "false").toBoolean
     19 
     20     Mailer.customProperties = Props.get("mail.smtp.host", "localhost") match {
     21       case "smtp.gmail.com" => // auto configure for gmail
     22         isAuth = true
     23         Map(
     24           "mail.smtp.host" -> "smtp.gmail.com",
     25           "mail.smtp.port" -> "587",
     26           "mail.smtp.auth" -> "true",
     27           "mail.smtp.starttls.enable" -> "true"
     28         )
     29       case h => Map(
     30         "mail.smtp.host" -> h,
     31         "mail.smtp.port" -> Props.get("mail.smtp.port", "25"),
     32         "mail.smtp.auth" -> isAuth.toString
     33       )
     34     }
     35 
     36     /*
     37     Mailer.devModeSend.default.set((m: MimeMessage) =>
     38       logger.info("Dev mode message:\n" + prettyPrintMime(m)))
     39     */
     40 
     41     if (isAuth) {
     42       (Props.get("mail.smtp.user"), Props.get("mail.smtp.pass")) match {
     43         case (Full(username), Full(password)) =>
     44           logger.info("Smtp user: %s".format(username))
     45           logger.info("Smtp password length: %s".format(password.length))
     46           Mailer.authenticator = Full(new Authenticator() {
     47             override def getPasswordAuthentication = new
     48                 PasswordAuthentication(username, password)
     49           })
     50           logger.info("SmtpMailer inited")
     51         case _ => logger.error("Username/password not supplied for Mailer.")
     52       }
     53     }
     54   }
     55 
     56   private def prettyPrintMime(m: MimeMessage): String = {
     57     val buf = new StringBuilder
     58     val hdrs = m.getAllHeaderLines
     59     while (hdrs.hasMoreElements)
     60       buf ++= hdrs.nextElement.toString + "\n"
     61 
     62     val out =
     63       """
     64         |%s
     65         |====================================
     66         |%s
     67       """.format(buf.toString(), m.getContent.toString).stripMargin
     68 
     69     out
     70   }
     71 }