Episode 3: Using the GAEJ Email Service

Hope you have got going with the Google App Engine for Java (GAEJ) through the first two episodes where we got started with it in the first episode and then wrote our own XMPP bot in the second episode. In case you still need to get an introduction to the mechanics, please do not hesitate from reading the first episode.

In this episode, we are going to look at the Email Service in GAEJ. You can read the official documentation provided at the Google site over here. We will be keeping this episode simple but the key to take away from this episode is the ease with which you can integrate email sending into your GAEJ hosted applications. Please note that the service currently provides the ability to only send emails/attachments, etc. There is no provision at this point of time for your GAEJ hosted application to receive emails.

Our approach to this episode will be consistent with the earlier ones where we will follow these steps:

  • See the application work first
  • Create a new project and write our code that utilizes the Email Service
  • Deploy and see it work

Email Service in Action

My approach in this and forthcoming episodes will be to focus on the Server side architecture and not much on the User Interface. What it means is that I could have demonstrated the Email Service by coding up a simple HTML form that accepts the To , Subject and Body of the Email to be sent and then it will hit a Server side script hosted in your GAEJ application and send off the email. But instead, I will assume that you are comfortable with whatever client (HTML, Flex, Java, etc) programming language and simply need a way to figure out what to do on the Server side. Hence we will focus on the Server side implementation.

To see the Email Service in Action, I have already the hosted the application that I wrote. The application id is gaejexperiments and hence available at http://gaejexperiments.appspot.com. In case you are still not clear on the Application Id, I suggest you read the first episode here.

To send an email, we will use a REST like style to invoke the Email Service. This is nothing much a servlet that has been hosted in my gaejexperiments application. To invoke the Email Service, all you need to do is punch in the following line in your favourite browser (IE, Firefox, Chrome, Safari,etc) and press enter:

http://gaejexperiments.appspot.com/gaejemail?email_to=[YourEmailId]&email_subject=[EmailSubject]&email_body=[EmailBody]

You need to substitute the values [YourEmailId],[EmailSubject] and [EmailBody] with your email id, a sample subject and a sample body (message text). Please make sure to encode your text as appropriate in case you have special characters, whitespaces, etc.

An example is shown here:

http://gaejexperiments.appspot.com/gaejemail?email_to=romin.k.irani@gmail.com&email_subject=Hi&email_body=Test

This should send out an email (on my behalf) and you will see a plain text message returned by our Service, which will indicate if it succeeded or failed in sending out the email. The sender of the message is coded in the service itself and we are not giving a provision here to specify that. It is just the way that I have designed the service and you can do it your way.

Remember that our application delivers the message onto the Google Infrastructure to deliver the message and then it will take over and try to deliver the message. That is pretty much standard stuff.

Develop our Project and utilize the Email Service

The first thing to do is to create a New Google Web Application Project. Follow these steps:

1. Either click on File –> New –> Other or press Ctrl-N to create a new project. Select Google and then Web Application project. Alternately you could also click on the New Web Application Project Toolbar icon as part of the Google Eclipse plugin.
2. In the New Web Application Project dialog, deselect the Use Google Web Toolkit and give a name to your project. I have named mine GAEJExperiments. I suggest you go with the same name so that things are consistent with the rest of the article, but I leave that to you.
3. Click on Finish

This will generate the project and also create a sample Hello World Servlet for you. But we will be writing our own Servlet.

Coding the GAEJEmailServlet.java

Create a new Servlet in your Project as shown below. I have created the GAEJEmailServlet.java in the package com.gaejexperiments.email. You can choose a package of your choice.  The code is straightforward and is listed below:

 

package com.gaejexperiments.email;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class GAEJEmailServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {

String strCallResult = "";
resp.setContentType("text/plain");
try {
//Extract out the To, Subject and Body of the Email to be sent
String strTo = req.getParameter("email_to");
String strSubject = req.getParameter("email_subject");
String strBody = req.getParameter("email_body");

//Do validations here. Only basic ones i.e. cannot be null/empty
//Currently only checking the To Email field
if (strTo == null) throw new Exception("To field cannot be empty.");

//Trim the stuff
strTo = strTo.trim();
if (strTo.length() == 0) throw new Exception("To field cannot be empty.");

//Call the GAEJ Email Service
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("#YOUR EMAIL ADDRESS HERE#"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(strTo));
msg.setSubject(strSubject);
msg.setText(strBody);
Transport.send(msg);
strCallResult = "Success: " + "Email has been delivered.";
resp.getWriter().println(strCallResult);
}
catch (Exception ex) {
strCallResult = "Fail: " + ex.getMessage();
resp.getWriter().println(strCallResult);
}
}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}

}

 

Let us go through the main pieces of the code:

  1. I have provided both GET and POST handlers in the servlet and the POST handler simply invokes the GET handler here.
  2. Then we parse the request parameters for the recipient email address (email_to) and the subject and body of the email i.e. email_subject and email_body respectively.
  3. We do some basic validation on the email_to field to make sure that it is not empty. I am currently not doing at validation on the subject and body fields. Additionally, you can easily modify this to receive more than one email address and loop through them yourself.
  4. Finally we have the block of code that sends email. This is pretty much standard JavaMail stuff that is used over here.  We get a mail session object. Then we create the MimeMessage in which we can populate the sender (from Email id), the recipient and finally the subject and body. We use the Transport object to send the email out and return back a plain text string indicating success or failure in delivering the email to the transport.
  5. Please note that the sender email id needs to be populated by you. I have intentionally left it as #YOUR EMAIL ADDRESS HERE# in the code above.

Configuring the Servlet in web.xml file

To complete our Servlet development, we will also need to add the <servlet/> and <servlet-mapping/> entry to the web.xml file. This file is present in the WEB-INF folder of the project. The necessary fragment to be added to your web.xml file are shown below. Please note that you can use your own namespace and servlet class. Just modify it accordingly if you do so.

 

<servlet>
<servlet-name>GAEJEmailServlet</servlet-name>
<servlet-class>com.gaejexperiments.email.GAEJEmailServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GAEJEmailServlet</servlet-name>
<url-pattern>/gaejemail</url-pattern>
</servlet-mapping>

 

Deploy the Application and utilize it

To deploy the application, you will need to first create your Application ID. The Application Identifier can be created by logging in at http://appengine.google.com with your Google Account. You will see a list of application identifiers already registered under your account (or none if you are just getting started). To create a new Application, click on the Create Application button and provide the Application Identifier as requested. Please note this name down since you will be using it for deployment.

For e.g. I have registered an application identifier named gaejexperiments.

To deploy the application, follow these steps (they should be familiar to you now):

  1. Click on the Deploy Icon in the Toolbar.
  2. In the Deploy dialog, provide your Email and Password. Do not click on Deploy button yet.
  3. Click on the App Engine Project settings link. This will lead you to a dialog, where you need to enter your Application ID [For e.g. my Application Identifier gaejexperiments]
  4. Click on OK. You will be lead back to the previous screen, where you can click on the Deploy button. This will start deploying your application to the GAEJ cloud. You should see several messages in the Console window as the application is being deployed.
  5. Finally, you should see the message “Deployment completed successfully”.

This means that you application is ready to serve and you can verify the Email service by invoking the appropriate url which you can punch into your browser. The format will be the following:

http://[YourApplicationId].appspot.com/gaejemail?email_to=[YourEmailId]&email_subject=[EmailSubject]&email_body=[EmailBody]

Moving forward

In this episode, we have seen how to utilize the Email Service provided by the Google App Engine. The code that we covered is straightforward to implement in your application. Do note once again that the Email Service currently does *not allow* for functionality that can receive emails. You can study the JavaMail API in more detail to understand how to do things like sending attachments in your email too. You can do that using the Google App Engine Email Service.

The other key thing to take away from this episode is also a focus on the server side api rather than building HTML front-ends, etc. I leave that to the user to design and implement since invoking a standards based HTTP GET or POST is now possible in almost any client programming platform.

In the next episode, we shall look at the Networking API available under GAEJ. The focus will be on invoking extrernal URLs and consuming external Web Services or even RSS feeds.

Till the next episode, good bye and happy coding!

Read more Episodes on App Engine Services

 

Advertisements

15 thoughts on “Episode 3: Using the GAEJ Email Service

  1. Hello, i’m from peru donit speak english.
    i have a question

    my app its similar to code is. NO SEND MESSAGE TO MY EMAIL TEST.. !! ??

    1. Let me understand. Did you:
      1) Try to run the code in the episode and it did not work as mentioned?
      or
      2) Do you have another GAE Application in which you are trying to send an email and it is not working?

      Let me know so that I can help you better.

      Thanks
      Romin

    1. Could you provide some more details? Did you check the logs via the console ? Please put in some additional logger statements, that might help.

      Thanks
      Romin

  2. Hi
    In the Servlet,you are actually calling doGet from doPost.this limits the number of characters sent through mail.i mean to say Post method supports way more characters than Get method.
    But, by using only Post Method ,i am not able to get the parameter values.cos getParameter doesnt work for Post Method. Do you know any workaround which allows me to send lengthy mails?
    Thanks

    1. Hi,

      My intention in the episodes is only to demonstrate the AppEngine SDK features. I do not intend to explain all best practices in Java coding, etc. So your points could be valid for the task that you are trying to do. I suggest you look up necessary documentation for the respective APIs.

      Thanks
      Romin

  3. Hello Sir..I am a student intrested in GAEJ concepts and this blog is very useful to me for increasing my knowldge abt GAE…while accessing the above application I observed the following error in my Log Console

    [05/Dec/2010:05:57:44 -0800] “GET /gaejemail?email_to=usssai52256@yahoo.com&email_subject=hai&email_body=hello HTTP/1.1” 404 0 “http://myemailsai.appspot.com/index.html” “Mozilla/5.0 (Windows NT 5.1; rv:2.0b7) Gecko/20100101 Firefox/4.0b7,gzip(gfe)” “myemailsai.appspot.com” ms=1 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000041

    I know that the problem is in my index.html but I am unable to decide what to do in that file..I simply copied ur actual http://gaejexperiments.appspot.com/email.html FrontEnd code and copied in my index.html.

    So please I request you to answer my amateur question patiently and help me out in this.

    Looking Forward to ur Reply…

    1. Ah!!Its fine now Im able to access the file well..thank you! All of ur articles are brilliant

      Waiting for ur 2nd ebook

    1. As per the documentation, the From Email Address can be only one of the following:

      • -The address of a registered administrator for the application
      • -The address of the user for the current request signed in with a Google Account. You can determine the current user’s email address with the Users API. The user’s account must be a Gmail account, or be on a domain managed by Google Apps.
      • -Any valid email receiving address for the app (such as xxx@APP-ID.appspotmail.com).

      I believe this is needed otherwise it could get used as SPAM Engine.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s