Grails template for email
In Grails, you can use the Email
class from the grails-plugin-mail
plugin to send emails. Here is an example of a Grails template for an email:
Email.groovy
import grails.plugin.mail.MailMessage
class Email {
String to
String subject
String body
def send() {
MailMessage mail = new MailMessage()
mail.to = to
mail.subject = subject
mail.body = body
mail.send()
}
}
This template defines a Email
class with three properties: to
, subject
, and body
. The send()
method uses the MailMessage
class from the grails-plugin-mail
plugin to send the email.
Usage
To use this template, you can create an instance of the Email
class and set its properties:
def email = new Email(to: '[email protected]', subject: 'Hello', body: 'This is a test email')
email.send()
You can also use the Email
class as a service, injecting it into your controllers or services:
class MyController {
def emailService
def index() {
def email = new Email(to: '[email protected]', subject: 'Hello', body: 'This is a test email')
emailService.sendEmail(email)
}
}
Configuring the email plugin
To use the Email
class, you need to configure the grails-plugin-mail
plugin in your Config.groovy
file:
grails {
mail {
host = 'smtp.example.com'
port = 587
username = 'your-email-username'
password = 'your-email-password'
props = ['mail.smtp.auth': 'true']
}
}
This configuration sets up the email plugin to use a SMTP server with the specified host, port, username, and password.
Additional features
The Email
class can be extended to include additional features, such as:
- Attachments: You can add attachments to the email by creating a
File
object and setting itsname
andbytes
properties. - HTML content: You can set the
body
property to a string containing HTML content. - CC and BCC recipients: You can add CC and BCC recipients by setting the
cc
andbcc
properties.
For example:
def email = new Email(to: '[email protected]', subject: 'Hello', body: '<html>This is a test email</html>')
email.cc = ['[email protected]']
email.bcc = ['[email protected]']
email.attachments = [new File('path/to/attachment.txt')]
email.send()