Grails 3 Send Email Example

by Didin J. on Feb 28, 2017 Grails 3 Send Email Example

An example of sending email using Grails 3 and Mail Plugin with various mail configuration.

Most of the web application or website require sending the email to their user or customer. It can be done easily in Grails 3 with just a few configurations in Grails 3 application. The Grails mail plugin provides a convenient DSL for sending the email. It supports plain text, HTML, attachments, inline resources, and i18n among other features. There is some library that can use for sending an email, but right now we are using Grails Mail Plugin. You can see more about this plugin here.

Table of Contents:

Let's jump to the example.

Create Grails 3 Application

As usual, in our tutorial always started with project or application creation from scratch. We assume that you already install required tools like Grails 3 and JDK 8. Open your terminal, command or git bash then go to your projects directory. Right here, type Grails command for creating a new application.

grails create-app GrailsMailExample

Go to the newly created application folder.

cd GrailsMailExample

Now enter the Grails 3 interactive console by typing this command.

grails

Compile your new Grails 3 application inside Grails 3 interactive console. This will download a lot of library and dependencies.

compile


Add Grails Mail Plugin

To add mail plugin, open and edit 'build.gradle' file using your editor or IDE. Add this line of dependency.

compile "org.grails.plugins:mail:2.0.0.RC6"

This is the last version of Grails Mail Plugin that updates a year ago. But this is still compatible with the latest Grails 3.2.6. Compile the application to download required dependencies again.

compile

Configure Grails Mail Plugin

There is a different configuration of this Mail Plugin, depends on SMTP mail service provider that used. For now, we are using Gmail as an example of sending an email. Open and edit 'grails-app/conf/application.yml' then add these lines of configurations.

grails:
     mail:
          host: "smtp.gmail.com"
          port: 465
          username: "[email protected]"
          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"

Don't forget to turn on access from a less secure app in your Gmail account configuration, otherwise, Google will block it and return this error.

2017-02-28 10:14:56.090 ERROR --- [nio-8080-exec-8] o.g.web.errors.GrailsExceptionResolver   : AuthenticationFailedException occurred when processing request: [POST] /emailSender/


Create Grails Controllers and Views for Testing

For testing this configuration, we need a view with a form that contains address textbox, mail body Textarea and sends button. Create a new controller using this command in Grails interactive console.

create-controller EmailSender

Create new 'index.gsp' file in `grails-app/views/emailSender` folder. Open and edit this new file then add these lines of HTML codes.

<!doctype html>
<html>
<head>
    <meta name="layout" content="main"/>
    <title>Email Sender</title>

    <asset:link rel="icon" href="favicon.ico" type="image/x-ico" />
</head>
<body>
    <div id="content" role="main">
        <section class="row colset-2-its">
            <g:if test="${flash.message}">
                <div class="message" role="alert">
                    ${flash.message}
                </div>
            </g:if>
            <h2>Email Sender Form</h2>
            <g:form controller="emailSender" action="send">
                <div class="fieldcontain">
                  <g:textField name="address" placeholder="[email protected]" required="" />
                </div>
                <div class="fieldcontain">
                  <g:textField name="subject" placeholder="Your Subject" required="" />
                </div>
                <div class="fieldcontain">
                  <g:textArea name="body" rows="5" cols="80" placeholder="Your message" required="" />
                </div>
                <fieldset>
                  <g:submitButton name="send" value="Send" />
                </fieldset>
            </g:form>
        </section>
    </div>

</body>
</html>

Now, open and edit emailSender controller then adds this method.

def send() {
    sendMail {
        to params.address
        subject params.subject
        text params.body
    }

    flash.message = "Message sent at "+new Date()
    redirect action:"index"
}

Next, you just can run your app and test send email using that form.


Example of Email HTML body

There is two-way sending email using HTML body. First, using the HTML tag as the string. For this method we can use text editor plugin for Textarea in views, for this example, we are using CKEditor. Open index.gsp then add this Javascript calls before the closing of head tag.

<script src="//cdn.ckeditor.com/4.6.0/full-all/ckeditor.js"></script>

Before the closing of the body tag, add this Javascript code.

<script>
  CKEDITOR.replace('body', {
    extraPlugins: 'codesnippet'
  });
</script>

In controller just change the text to HTML, like below code.

def send() {
    sendMail {
        to params.address
        subject params.subject
        html params.body
    }

    flash.message = "Message sent at "+new Date()
    redirect action:"index"
}

Now your email content will send same as what you see in CKEditor.

Second, using separate GSP template. Make sure you create the separate HTML file with GSP extension. In the controller make it like this.

sendMail {
    to params.address
    subject params.subject
    html view: "/emailSender/template", model: [param1: "value1", param2: "value2"]
}


Send Email with Attachment Example

To achieve this example add file input to the form.

<input type="file" name="attachment" />

Don't forget to add 'enctype' in the form tag.

<g:form controller="emailSender" action="send" enctype="multipart/form-data">

In the controller add this import.

import org.springframework.web.multipart.MultipartFile

Then change method send() like this.

def send() {
    def multipartFile = request.getFile('attachment')

    sendMail {
        multipart true
        to params.address
        subject params.subject
        html params.body
        if(multipartFile && !multipartFile.empty) {
          File tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + multipartFile.getOriginalFilename());
          multipartFile.transferTo(tmpFile);
          attach tmpFile
        }
    }

    flash.message = "Message sent at "+new Date()
    redirect action:"index"
}

Now, you can test send the email with the attachment. Another method to send the email with attachment describes well in the Plugin documentation. Here's the full view of sending email form with attachment.

 

Grails 3 Send Email Example - Full form


Another Example of SMTP Configuration

Here's I show you a few configurations for the different SMTP server. This configuration is tested and working fine.

Amazon AWS SES

grails:
    mail:
        host: "email-smtp.us-east-1.amazonaws.com"
        port: 587
        username: "Access Key ID"
        password: "Secret Access Key"
        from: "[email protected]" # Your email that registered in AWS SES
        props:
            mail.smtp.auth: "true"
            mail.smtp.starttls.enable: "true"
            mail.from: "[email protected]"
        javaMailProperties:
            mail.smtp.auth: "true"
            mail.smtp.starttls.enable: "true"
            mail.from: "[email protected]"


Hotmail/Live

grails:
    mail:
        host: "smtp.live.com"
        port: 587
        username: "[email protected]"
        password: "yourpassword"
        props:
            mail.smtp.starttls.enable: "true"
            mail.smtp.port: "587"


Another configuration describes in Grails Mail Plugin documentation. For this example, you can find the source code on Github.

Please feel free to give your opinion or suggestion for this tutorial to make it more useful for everyone and everybody.

That just the basic. If you need more deep learning about Groovy and Grails you can take the following cheap course:

Thanks.

Loading…