Pither.com / Simon
Development, systems administration, parenting and business

HTML email from a GSP with the Grails mail plugin

The Grails mail plugin is an invaluable addition to most Grails based sites - it's a rare website that doesn't need to send email. Some really useful features have been sitting on it's todo list for a while, but it still does a lot as it is.

(Examples below are mostly stolen from the plugin documentation.)

It lets you send a string as a plain text email:

sendMail {     
  to "fred@g2one.com"     
  subject "Hello Fred"     
  body 'How are you?' 
}

Or send a string as an HTML email:

sendMail {
  to "fred@g2one.com"
  subject "Hello John"
  html '<b>Hello</b> World'
}

Then it gets really useful and lets you render your email content from a GSP:

sendMail {
  to "john@g2one.com"
  subject "Hello John"
  body(view:"/mail/confirmationRequest", model:[username:'john'])
}

This is especially handy when you want to send your mail from a service class or a Quartz job (as these places don't have easy access to the normal rendering methods).

The slight flaw with this is that the body() method defaults to creating a plain text email (contrary to what the documentation says - I'd fix it if the grails.org password reminder page accepted email addresses instead of usernames!) and there is no html(view:"...", model:[]) equivalent as there is for simple string parameters.

Instead for GSP templates, the body() method uses information embedded in the GSP document itself to decide if the email should be plain text or HTML. So to produce an HTML email, you need to add this to your GSP:

<%@ page contentType="text/html" %>

As I said above, the mail plugin documentation does talk about this, but it also says that HTML is the default, which appears (from reading the code and testing) not to be the case. You also need to be quite specific with the contentType string to get it to detect as HTML.

Comments

On Sept. 29, 2013, 9:04 a.m. Nikolai said...

I have a problem with body encoding, cyrrilic text showing as abracadabra

On Oct. 10, 2013, 11:31 a.m. Simon Pither said...

Hi Nikolai,

This post is quite old, so if you're using Grails 2.0 or later you may have more success with the PageRenderer http://grails.org/doc/latest/api/grails/gsp/PageRenderer.html bean. See also http://grails.org/doc/latest/guide/introduction.html#webFeatures

For example:

def contents = groovyPageRenderer.render(view:"/emails/welcomeLetter", model:[user: user])
sendEmail {
to user.email
html contents
}

On June 29, 2022, 4:05 a.m. Georgina O'Keeffe said...

I have a small question

On June 29, 2022, 8:29 a.m. Simon Pither said...

Hi Georgina, happy to help if I can, please do ask.

Add a comment