I was trying to get my Lift web application to send out some mail through a Gmail account. I'm rusty with Java Mail so this took longer than it should have, so here's the code for anyone else it helps. The first big of code is just a bit of code to insert into the Boot class. I've put it in a separate method just to keep this code together, then I call it straight from the boot
method.
import javax.mail.{PasswordAuthentication, Authenticator} private def setupMailerForGmail() { // Set up mailing to mail through Gmail account System.setProperty("mail.smtp.starttls.enable", "true") System.setProperty("mail.smtp.ssl.enable", "true") System.setProperty("mail.smtp.host", "smtp.gmail.com") System.setProperty("mail.smtp.auth", "true") // Turn on display of emailing processing logs by setting this property... //System.setProperty("mail.debug", "true") Mailer.authenticator = Full(new Authenticator { override def getPasswordAuthentication = new PasswordAuthentication("accountname…@gmail.com", "password…") }) }
To send an email you can use something as short as:
import net.liftweb.util.Mailer.{To, From, PlainMailBodyType, Subject} import net.liftweb.util.Mailer … Mailer.sendMail(From("accountname…@gmail.com"), Subject("Just a test"), List(PlainMailBodyType("The body of the test message"), To("recipient_email_address…")) : _*)
Once this is working it's relatively straightforward to work out how to do XHTML mails and send to multiple recipients, etc.
The one bit of code that helped me the most was setting the mail.debug
system property which caused the Java Mail code to output a trace of the mail sending process and allowed me to spot that I had failed to enable SSL.