Pages

2010-05-16

App Engine email to 'admins' gotcha

I recently started adding email notifications to PicSoup (my GAEJ application). I followed the examples in the documentation and wrote a really simple function to allow me to send a simple text email to one recipient:
private void sendEmail(String recipientAddress, String recipientName, String subject, String message) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("my-admin-account@gmail.com", "PicSoup Admin"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress, recipientName));
        msg.setSubject(subject);
        msg.setText(message);
        Transport.send(msg);
        logger.info("Sent email to "+recipientAddress);
    } catch (Exception e) {
        logger.error("Failed to send email",e);
    }
}
Simple stuff, and almost identical to the documented example. Note that it uses the InternetAddress constructor that allows you to enter an address and a personal name.

This works really well and allows me to write simple calls like this:
sendEmail(p.getUser().getEmail(), p.getDisplayName(), "PicSoup info", "Your competition entry was successfully added. Good luck!");

This notifies a particular user and uses their settings to get the appropriate "personal name". I also wanted to use this call to send notifications to myself. Being the administrator I could do this using the Admins Emailed quota. To do this I thought I could use the special "admins" recipient with my sendEmail function like this:
sendEmail("admins", "PicSoup Administrators", "PicSoup info", "A new pic has been added.");

Sadly I discovered that this doesn't work. It silently fails to send the email to anyone! It turns out that this is because I have included "PicSoup Administrators" as the "personal name" in the InternetAddress object. In order to make this work I changed my sendEmail method to ignore the "personal name" for emails to admins:
private void sendEmail(String recipientAddress, String recipientName, String subject, String message) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("my-admin-account@gmail.com", "PicSoup Admin"));
        if ("admins".equals(recipientAddress)) {
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));
        } else {
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress, recipientName));             
        }
        msg.setSubject(subject);
        msg.setText(message);
        Transport.send(msg);
        logger.info("Sent email to "+recipientAddress);
    } catch (Exception e) {
        logger.error("Failed to send email",e);
    }
}