Attach file using grails mail

In Grails, you can attach a file to an email using the Mail class and the attach method. Here's an example:

import grails.mail.MailMessage

def mailService = new MailService()

def file = new File('path/to/your/file.txt')
def attachment = new Attachment(file, 'text/plain', 'file.txt')

def mail = new MailMessage()
mail.to = '[email protected]'
mail.subject = 'Test email with attachment'
mail.text = 'This is a test email with an attachment.'

mail.attachments = [attachment]

mailService.sendMail { msg ->
    msg.to = mail.to
    msg.subject = mail.subject
    msg.text = mail.text
    msg.from = '[email protected]'
}

In this example, we create a MailMessage object and set the to, subject, and text properties. We then create a new Attachment object, passing in the file, the MIME type, and the file name. We add the attachment to the attachments property of the MailMessage object.

Finally, we use the sendMail method of the MailService to send the email.

You can also use the attach method of the MailMessage object to attach a file:

def mail = new MailMessage()
mail.to = '[email protected]'
mail.subject = 'Test email with attachment'
mail.text = 'This is a test email with an attachment.'

mail.attach(new File('path/to/your/file.txt'), 'text/plain', 'file.txt')

mailService.sendMail { msg ->
    msg.to = mail.to
    msg.subject = mail.subject
    msg.text = mail.text
    msg.from = '[email protected]'
}

Make sure to replace path/to/your/file.txt with the actual path to the file you want to attach.

You can also use the attach method to attach multiple files:

def mail = new MailMessage()
mail.to = '[email protected]'
mail.subject = 'Test email with attachments'
mail.text = 'This is a test email with attachments.'

mail.attach(new File('path/to/your/file1.txt'), 'text/plain', 'file1.txt')
mail.attach(new File('path/to/your/file2.txt'), 'text/plain', 'file2.txt')

mailService.sendMail { msg ->
    msg.to = mail.to
    msg.subject = mail.subject
    msg.text = mail.text
    msg.from = '[email protected]'
}

This will attach both file1.txt and file2.txt to the email.