Sending mail on Google appengine with Grails
Sending emails with Google AppEngine is quite straight forward once you get a hang of things. I ran into some issues, for example I never got the high level api’s to work. The code executed but the emails were never received. Instead I went for Google AppEngines own “low level” api, it worked much better.
What I did is that I set up a really simple MailService, similar to that which is installed with the Mail plug in. However, I do not handle templates instead I just send strings with the mail message.
package mail
import com.google.appengine.api.mail.MailService
import com.google.appengine.api.mail.MailService.Message
import com.google.appengine.api.mail.MailServiceFactory
import javax.mail.MessagingException
import javax.mail.internet.AddressException
class MailService {
boolean transactional = true
def sendMail(subject, msgBody, too) {
try {
def service = MailServiceFactory.getMailService();
def msg = new com.google.appengine.api.mail.MailService.Message();
msg.setSender("<span style="color: #ff0000;">xxx</span>");
msg.setTo(too);
msg.setSubject(subject);
msg.setHtmlBody(msgBody);
service.send(msg);
} catch (AddressException e) {
// ...
} catch (MessagingException e) {
// ...
}
}
}
As you can see it is quite straight forward. I’d like to mention though that in the above code you see a red xxx. This is where you put your sender address. It needs to either be the email to an admin (registered developer) of the app, or it has to be a user logged in using Google’s own login.
With the low-level api it throws an exception like the one below:
Uncaught exception from servlet org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.IllegalArgumentException: Unauthorized Sender: Unauthorized sender
Good luck!