Grails emails

Grails provides a built-in support for sending emails through the grails.mail plugin. Here are the steps to send an email in Grails:

Step 1: Add the grails.mail plugin

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

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

Step 2: Configure the mail settings

In your Config.groovy file, add the following settings:

mail {
    host = 'your-smtp-host'
    port = 587
    username = 'your-email-username'
    password = 'your-email-password'
    props = ['mail.smtp.auth': 'true']
}

Replace the placeholders with your actual SMTP server settings.

Step 3: Send an email

You can send an email using the GrailsMail class:

import grails.mail.MailMessage

def mailService = new GrailsMail()

def message = new MailMessage()
message.from = 'your-email-username'
message.to = '[email protected]'
message.subject = 'Test Email'
message.text = 'This is a test email'

mailService.sendMail(message)

This code creates a new MailMessage object and sets the sender, recipient, subject, and body of the email. Then, it uses the sendMail method of the GrailsMail class to send the email.

Step 4: Use the MailService

In your Grails controller or service, you can inject the MailService and use it to send emails:

import grails.mail.MailService

class MyController {
    def mailService

    def sendEmail() {
        def message = new MailMessage()
        message.from = 'your-email-username'
        message.to = '[email protected]'
        message.subject = 'Test Email'
        message.text = 'This is a test email'

        mailService.sendMail(message)
    }
}

In this example, the MyController class injects the MailService and uses it to send an email in the sendEmail action.

Additional features

The grails.mail plugin provides additional features, such as:

You can explore these features by checking out the plugin's documentation and examples.