Grails email

Grails provides a built-in support for sending emails through the grails.mail plugin. Here's a step-by-step guide on how to use it:

Step 1: Add the grails.mail plugin to your project

In your BuildConfig.groovy file, add the following line:

plugins {
    //...
    mail: '1.3.1'
}

Step 2: Configure the mail settings

Create a mail configuration file in the grails-app/config directory, e.g., mail.groovy. This file will contain the mail settings, such as the SMTP server, username, and password.

Here's an example mail.groovy file:

grails {
    mail {
        host = 'smtp.gmail.com'
        port = 587
        username = '[email protected]'
        password = 'your_password'
        props = ['mail.smtp.auth': 'true']
    }
}

Step 3: Send an email

To send an email, you can use the GrailsMail class, which is part of the grails.mail plugin. Here's an example:

import grails.mail.MailMessage

def sendEmail() {
    def mailMessage = new MailMessage()
    mailMessage.subject = 'Hello from Grails!'
    mailMessage.text = 'This is a test email sent from Grails.'
    mailMessage.to = '[email protected]'
    mailMessage.from = '[email protected]'

    GrailsMail.sendMail(mailMessage)
}

In this example, we create a MailMessage object and set its properties, such as the subject, text, to, and from addresses. Then, we call the sendMail method of the GrailsMail class to send the email.

Step 4: Use the sendMail method in a controller or service

You can use the sendMail method in a controller or service to send emails. For example, you can create a controller method that sends an email when a user submits a form:

class MyController {
    def sendEmail() {
        // Get the form data
        def name = params.name
        def email = params.email

        // Create a MailMessage object
        def mailMessage = new MailMessage()
        mailMessage.subject = 'Hello from Grails!'
        mailMessage.text = "Hello $name, your email is $email."
        mailMessage.to = email
        mailMessage.from = '[email protected]'

        // Send the email
        GrailsMail.sendMail(mailMessage)
    }
}

That's it! With these steps, you should be able to send emails using the grails.mail plugin in your Grails application.