Setting up mail support in your Grails application

At some point in your Grails application development you’ll find yourself invariably needing your application to send mail.  With the Grails mail plugin, it’s a snap.  Essentially the mail plugin is a wrapper to configure a Spring MailSender instance.  And the Spring MailSender is a wrapper to the JavaMail API. As long as you know about these libraries and implementation details, using Grails mail is pretty straightforward.  First start by adding following dependency reference to your plugins section of your project’s BuildConfig.groovy file:

 
    plugins {
        //.. other plugs 
        compile ":mail:1.0.1"
    }

You can also use the “standard” approach to install the plugin as well:

grails install-plugin mail

Next you need to configure the mail plugin to know what smtp server to use in Config.groovy:

 

grails {
    mail {
        host = "mail.yourdomain"
        port = 25
        props = ["mail.smtp.from":"david.orrissjr@yourdomain"]
    }
}

The ‘props’ section can be populated with any of the properties defined in the JavaMail API to leverage the various SMTP features.  Take note to be very careful with them and read the RFCs on the SMTP protocol before you attempt to use something you aren’t familiar with.

Finally a simple call in your controller to the sendMail method that you provide a closure for is all that’s needed to send an email.

 
class MailSendController {

    def sendMessage () {
        sendMail {
            to "davido@yourdomain"
            subject "Hello from the sendmail plugin"
            body "Hello from the sendmail plugin.  Here's the email you wanted."
        }

        render "EMail sent."

    }

} 

There are plenty of other ways you can leverage the mail plugin as well.  You can find more details on the grails mail plugin page:

http://grails.org/plugin/mail

And the Mail Plugin documentation page: http://gpc.github.io/grails-mail/

To see what other features you can leverage you should also read about the JavaMail plugin itself and the SMTP properties that can be set in the JavaMail session object.  You can find out more about that subject here:

http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html

Leave a Reply

Your email address will not be published. Required fields are marked *