Configuring multiple senders in Grails Mail plugin

14 / Jun / 2010 by Abhishek Tejpaul 2 comments

In one of the recent projects, we had to set up a system where emails for different purposes (i.e registration, error reporting etc.) were to be sent out from different email accounts. We were using the Grails Mail plugin which does not provide a clear way to set-up or configure multiple email addresses. With the help of my colleague, Chandan Luthra, I tried to dig into the workings of plugin and found out that Mail plugin injects the properties such as username, password etc. through a bean named mailSender. So we just did the following to customize/configure these properties on the fly from the controller or a service:

CH.config.grails.mail.default.from = "username@domain.com" // Mail plugin uses this to connect to the account in e-mail provider's server. So it should be set.
mailSender.username = "username@domain.com"
mailSender.password = "sample123!"

And yes, once you are done with your email sending functionality you can set mailSender properties back to the default settings set originally in Config.groovy. Your service/controller code could look something like this:

// Store the default mail settings in variables
def defaultFrom = CH.config.grails.mail.default.from
String oldUsername = mailSender.username
String oldPassword = mailSender.password

// Change the properties here; send the email
try {
CH.config.grails.mail.default.from = "username@domain.com"
mailSender.username = "username@domain.com"
mailSender.password = "sample123!"
mailService.sendMail {
to(['exampple1@domain1.com', 'example2@domain2.com'].toArray())
subject("Example Subject")
body("Sample body")
}
}
catch (Exception e) {
// catch block code
}
// Set the original settings back
finally {
CH.config.grails.mail.default.from = defaultFrom
mailSender.username = oldUsername
mailSender.password = oldPassword
}

I guess this scenario can be quite prevalent in many projects. Hope you find the blog useful.

– Abhishek Tejpaul

Intelligrape Software Pvt. Ltd.

[www.intelligrape.com]

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. wes Kim

    Hi Burt,

    If this isn’t thread-safe, then how would address this potential problem?
    Can you please add your input Burt?

    Reply
  2. Burt Beckwith

    This isn’t thread-safe. The config and the mailSender bean are singletons. So you run a high risk that when sending multiple concurrent emails, the settings will overlap.

    Reply

Leave a Reply to wes Kim Cancel reply

Your email address will not be published. Required fields are marked *