Sending Email In Grails

CFML developers have it easy when it comes to sending email.  Set up your mail server in the administrator and use the <cfmail> tag and you’re all set.  Sending email with Grails requires a bit more work, but not much.  In this post we’ll take a look at one way to send email from your Grails application.

Grails does not ship with a method to send email ‘out of the box.’  Luckily the Java world has solved the problem of sending email long ago.  In fact, ColdFusion itself uses JavaMail behind the scenes to send your messages when you use the <cfmail> tag.  Wouldn’t it be sweet if we could also use JavaMail in our Grails application?

With the Grails mail plugin we can do just that.  Let’s take a look at how easy it is to install the plugin and send email from our application.

To install the plugin, run the following command:

grails install-plugin mail

Once installed the mail plugin can now be injected anywhere you need it in your Grails app.  In fact, the plugin automatically injects the sendMail method into all of your controllers to make things even easier.  There are a number of config settings for the mail plugin.  These settings are added to your conf/Config.groovy file.  By default, the plugin assumes that your mail server is running on port 25 of localhost, but you can configure the plugin to use any mail server (including Gmail) to send mail.  In this example I’ve added a simple config to the development environment.  Note that I’ve added an overrideAddress for this environment so that no actual emails are sent while I’m testing the app in development.  I’ve also included the host and port (even though they are the same as the defaults) to illustrate how those values are set should you need to change them.

A full exploration of the plugin is a bit beyond the scope of this post.  Take a look at the plugin documentation for further information on configuration including how to send attachments.

Now that we’ve got everything set up, let’s take a look at a simple example using “real world” requirements.  Systems often have users, and when new users are created we often send them an email to let them know that an account has been created for them.  It should certainly go without saying, but please note that in a “real world” application you would not store passwords in plain text.  Ever.  This is a contrived example.  You have been warned.  

To get started, set up a simple domain class for our User.

Now scaffold out a controller and views .  You can do this via grails generate-all or by using the appropriate method within your chosen IDE’s graphical interface.  Within the generated controller locate the save() method that was created for you.  This method is called whenever the form within the views/user/create.gsp view is posted.  Within the save method we’ll first verify that the userInstance is truly a new instance and if it is a new instance we’ll send the user an email to let them know their account has been created.

Note that if I was not running a mail server and tried to submit the user form at this point I would receive a big fat runtime exception since the plugin attempts to connect to localhost:25 to send the message.  For the purpose of this demo I have set up a simple mail server using Apache James.  Now, when I submit the new user form the message is properly sent, but since I used an invalid override address the message gets stuck in James’ outgoing folder.  If we navigate to that folder and open the ‘FileStreamStore’ file with our favorite text editor we can take a look at the contents of the message which will look something like this:

And that’s all it takes to get started sending email from your Grails application.

The code for this post and many other ‘CFML features in Grails’ examples can be found on Compile, Dammit’s GitHub.

Todd began his journey in development with ColdFusion in 2004. Like a lot of ColdFusion developers he was the "computer guy" on his team and was assigned to a small team of developers to build intranet applications. Due to the nature of such an assignment this often led to being the sole developer on a project - responsible for everything from the server side logic, to database queries, to front end architecture and design. These responsibilities combined well with his natural desires to learn new things and soon led to him diving deep into Ajax, Flex ColdFusion frameworks and Object Oriented design patterns and methodologies. After joining Booz Allen Hamilton in 2011 he has extended his learning into many newer front end and back end frameworks and toolsets - the latest passion being Groovy/Grails and HTML5/JavaScript frameworks. Todd frequently speaks at industry conferences and has been published in numerous technical journals on various topics. When not slanging code he can be found at one of his children's various activities, hanging out with his wife or pwning n00bs on the latest edition of Call Of Duty.

Posted in Grails for CFML Developers, Groovy/Grails
12 comments on “Sending Email In Grails
  1. Rather than using install-plugin, the preferred approach now is to add a plugin dependency in BuildConfig.groovy. Each plugin page (in this case http://grails.org/plugin/mail ) has the syntax to use, so for mail it’d be ‘compile “:mail:1.0″‘

  2. Scott Stroz says:

    Burt – Thanx for that bit of advice.

  3. Having “override” support built in is -so- damn useful (and smart).

  4. Brian Kotek says:

    If you’re using GStrings (yes, they’re really called that), I’m pretty sure you can get rid of the ugly string concatenation and just use expressions:

    “”"
    Your username is: ${ userInstance.username }
    Your password is: ${ userInstance.password }
    …etc.
    “”"

    • Todd Sharp says:

      Thanks Brian.

      You can also actually use templates like this:

      sendMail {
        to "john@g2one.com"
        subject "Hello John"
        html g.render(template:"myMailTemplate")
      }
      
  5. Willy Gielen says:

    Need to be careful when sending mails from a quartz job, cause encoding does not work (or it didn’t work for me). Moving the sendmail to a service and calling the service from the quartz job fixed the problem.

  6. Todd Sharp says:

    Thanks Willy. Did you try just injecting the mailService itself into the job?

  7. A while back I had to start sending HTML emails from Clojure and didn’t find a nice library so I had to roll my own wrapper for JavaMail. The designers of the JavaMail API must have been on serious drugs when they thought that up – it’s a horrible API to work with! Took me quite a while to wrap it up in a (send-email …) function – which looks a lot like the Groovy sendMail offering – and that made me really appreciate the CFML approach in this case.

    Since then folks have pointed out a couple of new Clojure libraries for dealing with email that would have made my life much simpler… Our setup has evolved nicely (and includes the per-environment ability to override the To: address, like the Grails plugin, as well as integration with our email status tracking system for bounces / invalid email addresses).

  8. Nguyen Le says:

    I set send email account but mail plugin don’t send by that account. How to resolve, please???

Leave a Reply