Wednesday, February 11, 2009

Grails Mail plugin usage

Essential feature of every web application is possibility to send emails. Traditionally when You will look through Grails reference You will find page concerning proposals for email integration in Grails. But approaches mentioned there are not perfect and their implementation in our application was quiet hard. So I decided to look for another solutions and found excellent Grails Mail Plugin. You can easily install it using command:
grails install-plugin mail

Grails Mail Plugin integration is very simple - everything You need is to dynamically inject mail service into Your service. After that You can use its sendMail method for sending email:
class MyService {

// Dynamic injection happens here.
MailService mailService

def someMethod() {
// Some logic.
mailService.sendMail {
to "email@mail.com"
from "youraccount@gmail.com"
subject "Test mail"
html """Hello!
This is a test email. """
}
}
}
Do not forget to configure Your mail server, configuration is located in grails-app/Config.groovy file. In my example it can be similar to listed below:
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "youraccount@gmail.com"
password = "yourpassword"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}

One topis is not covered - unit and integration testing of mail service. You will not believe but only thing You need is to initialise mail service in Your integration or unit test and connent it to my service. Short example:
class MyServiceTests extends GrailsUnitTestCase {

MyService myService

void setUp() {
// Do not forget to call super method at first.
super.setUp()

// Initialize the my service.
userService = new UserService()
// Initialize the mail service and
// connect it to my service

userService.mailService = new MailService()
}

// Some tests.

}
That's all concerning Grails Mail Plugin, hope You enjoyed it.

3 comments:

  1. Hi, I installed the plugin but I'm getting the following error,
    Groovy:unable to resolve class MailService

    Do I need to import some jars in the classpath?

    ReplyDelete
  2. A little late... but maybe this will help someone... You have to import grails.plugin.mail..

    ReplyDelete
  3. How do we config for MS Exchange Server?

    ReplyDelete