Receiving Mail In Java

Receiving email is a bit harder than sending it. First, we need to inform App Engine that this application is allowed to receive mail. In the /war/WEB-INF/ directory there is a file marked appengine-web.xml. Write the below line into that file:

<inbound-services> <service>mail</service> </inbound-services>

Now we need to map a servlet to handle all of the incoming email. Go into web.xml (in the same directory) and put in the following lines:

<servlet>
    <servlet-name>ReceiveMail</servlet-name>
    <servlet-class>com.example.ReceiveMailServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ReceiveMail</servlet-name>
    <url-pattern>/_ah/mail/*</url-pattern>
</servlet-mapping>

This informs App Engine that there is a servlet called com.example.ReceiveMailServlet (modify the name to match your code), and it is responsible for handling all incoming email (it handles all requests directed to /_ah/mail/ which is where App Engine sends the mail).

In the servlet handling the incoming email, paste this doPost() function:

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {   

try {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null); 
    //May throw a MessagingException if incoming message is malformed.
    MimeMessage message = new MimeMessage(session, req.getInputStream());
}
catch (MessagingException e) {
    System.out.println("This message was malformed. Stopping.");
}

}//end doPost

From here, we can retrieve the from address and the subject with a few lines:

String from = message.getFrom()[0].toString();//Get the first From address listed.
String subject = message.getSubject();

The content of the email can be extracted using the getContent() function of MimeMessage.