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("xxx");
 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!

Bookmark and Share

, ,

  1. #1 by Huy on February 2, 2010 - 07:48

    Hi,
    I did like you but still have the problem of:
    java.lang.IllegalArgumentException: Unauthorized Sender: Unauthorized sender

    Can you tell me why? Can you show me the code that work for you?

    Many thanks

  2. #2 by Morten on February 3, 2010 - 09:33

    Hi Huy!

    Have you made sure that you are sending from a registered developer of the application? In the end of the post it says: “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.”

    I my self have registered an email address called “robot@…com” to send the messages.

(will not be published)