Sunday, April 12, 2009

More on Grails Mail

by Richard Vowles

Actually testing the grails mail plugin and having it sending email and then decoding the results were a little more difficult that expected. dumpster 1.6 (last updated in 2005) was buggy for MIME messages - it didn't obey the ordering of the message headers or keep the line feeds in emails.

Then it was finding a way to decode the message so I could spelunk through it and ensure it matched what was required. I'm almost finished now - the attachments file files and byte arrays work, but the InputStream is giving me a Bad file descriptor which I think might be related to trying to read the stream multiple times, but it happens in native code so I'm not sure.

I also have to check how to check JNDI data sources and then I thought I would check the JIRAs for other issues.

A sample method looks like this:

void testSendMailViewWithTags() {
def mailService = new MailService ()
mailService.mailSender = mailSender

def ctx = RequestContextHolder.currentRequestAttributes ().servletContext
def applicationContext = ctx[GrailsApplicationAttributes.APPLICATION_CONTEXT]

mailService.groovyPagesTemplateEngine = applicationContext.getBean (GroovyPagesTemplateEngine.BEAN_ID)

mailService.sendMail {
to "fred@g2one.com"
subject "Hello John"
body (view: '/_testemails/tagtest', model: [condition: true])
}

assertEquals 1, server.receivedEmailSize

MimeMessage m = new MimeMessage ((Session) null, new StringBufferInputStream (server.receivedEmails[0].toString ()))

MimeMultipart content = m.content
assertEquals 1, content.count
assertEquals 1, content.getBodyPart(0).getContent().getCount() // only 1, it should be text
assertEquals "text/plain", content.getBodyPart(0).getContent().getBodyPart(0).getContentType().split(";")[0]
assertEquals "Condition is true", content.getBodyPart(0).getContent().getBodyPart(0).getContent().trim()

mailService.sendMail {
to "fred@g2one.com"
subject "Hello John"
body (view: '/_testemails/tagtest', model: [condition: false])
}

assertEquals 2, server.receivedEmailSize

m = new MimeMessage ((Session) null, new StringBufferInputStream (server.receivedEmails[1].toString ()))

content = m.content
assertEquals 1, content.count
assertEquals 1, content.getBodyPart(0).getContent().getCount() // only 1, it should be text
assertEquals "text/plain", content.getBodyPart(0).getContent().getBodyPart(0).getContentType().split(";")[0]
assertEquals "", content.getBodyPart(0).getContent().getBodyPart(0).getContent().trim()
}

No comments: