Sending e-mails with Grails: the simple way
Sending e-mails with Grails can be quite complicated (yeap, I know about the Mail Plugin, but I also know many people who had some problems with it AND it’s a Grails only alternative).
If you don´t want to use a plugin, you can always count with the Java Mail API, or even the Spring Framework support for it, right? Yeah, right: but at least for me, it seems like a to complex solution for a simple need. So, I started my quest for a simple way to do it. The solution I found was right in front of me all the time (so usual…): Commons E-mail, which is part of the Apache Commons project!
To show how you can use it, here is a small snippet:
import org.apache.commons.mail.SimpleEmail
class MailService {
boolean transactional = false
// I added the configuration on the same class just for the sake of simplicity (you should NEVER do this on a real case)
String host= "your.mail.ver"
String username = "your.login"
String password = "your.password"
String from = "me@me.com"
Integer port = 465
def send(String subject, String msg, String to) {
//SimpleEmail is the class which will do all the hard work for you
SimpleEmail email = new SimpleEmail()
email.setHostName(host)
email.addTo(to)
email.setFrom(from)
email.setSubject(subject)
email.setMsg(msg)
//If you need authentication, this is the method
email.setAuthentication(username,password)
// If you need to specify your smtp port, this is how to
email.setSmtpPort(port)
// So all you need to do is call the method send() and your e-mail will be delivered (at least in theory)
email.send()
}
}
Just like I wanted: simple!
Dependencies
All you need is JAF, which may be downloaded on the following link: http://java.sun.com/javase/technologies/desktop/javabeans/jaf/index.jsp
Where to download Commons E-mail: http://commons.apache.org/email/
Leave a Reply
Aug 24th 2009 • 11:08
by Tom
Nice snippet. I didn’t know about SimpleEmail
Reply
Aug 24th 2009 • 19:08
by Matt Passell
To make the code even more “Groovy”, you could take advantage of “with” (see Getting Groovy With “with”) and not have to repeat your references to the email variable (comments removed for the sake of brevity):
SimpleEmail email = new SimpleEmail()email.with {
setHostName(host)
addTo(to)
setFrom(from)
setSubject(subject)
setMsg(msg)
setAuthentication(username,password)
setSmtpPort(port)
send()
}
Reply
admin Reply:
August 25th, 2009 at 16:39
Yeap! Looks great like this!
But in this case, I think that a more “Java” approach is enough (after all, it was one of my requisites :) )
Reply
Aug 29th 2009 • 06:08
by Ron Barlag
I’m looking for a means to batch process mail in gmail using Groovy.
Of course there is the javamail api, but do you know something similar like the a apache commons simple mail?
Reply
May 19th 2010 • 00:05
by Batman Lot
hello!, thanks for the info, this post was really nice.
Reply