Wednesday, September 4, 2013

Sending Email from your Grails Application : A Tutorial

Here is how you can simply send an email from your Grails Application.


Step 1: In BuildConfig.groovy add the ff code in plugins{} tag,

// Grails mail plugin
compile ":mail:1.0.1"

Step 2: In Config.groovy, add the ff code
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "sample@gmail.com"
password = "fakeP@SSw0Rd"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}


This is for gmail. If you want to send email from other email service providers like "Yahoo", you might need to change this settings.

Step 3: In your service class, inject mailSerice as

def mailService

Your method might look something like this.

private void sendEmail(final User user) {

mailService.sendMail {

multipart true

to user.email

subject messageSource.getMessage("message.subject", null, "Body of the message.", null)

body messageSource.getMessage("message.body", null, "Body of the message.", null)
}
}

The subject and the body are defined in messages.properties as

#Email messages
message.subject=My Subject
message.body=This is the body of the message. Please add the correct message here.

*****************************************************************************

A more complicated example (that attaches a PDF file and the subject has additional custom attributes) is presented as follows.

private void sendEmail(final User user) {

mailService.sendMail {

multipart true

to user.email

subject messageSource.getMessage("payment.transaction.message.subject",
[user.name, new SimpleDateFormat(Constants.DATE_FORMAT).format(new Date() - 1)].toArray(), "Report.", null)

subject messageSource.getMessage("message.subject", null, "Body of the message.", null)

body messageSource.getMessage("message.body", null, "Body of the message.", null)

attachBytes ReportPDFFileName,
"application/pdf",
new File(ReportPDFFileName).readBytes()
}
}

The subject and the body are defined in messages.properties as

#Email messages
message.subject=My Subject for user name {0} On date {1}
message.body=This is the body of the message. Please add the correct message here.