Generic Service – HTML Form Post to Email Servlet

Lucas Jellema 2
0 0
Read Time:4 Minute, 38 Second

This article is about a generic service that takes a simple HTML Form Post and turns it into an Email. It is not revolutionary – but useful nevertheless. Besides, it is the first installment in a series that works towards a SOA implementation. We will implement a Business Process in this series using Oracle BPEL PM 10.1.3. The first step in this process is a Web Site (in this case even a static HTML document), that posts a form with the collected user input. The Form Submit – and therefore the sent email – is the trigger that starts the process.

We will see in this article how we can post an HTML form to any URL, in this specific case one that represents a generic Java Servlet but in the exact same manner also a PHP, PERL, ASP.NET or any other CGI like web application, that turns it into a an email. The HTML Document is completely decoupled from this Email Service – very SOA style!

 

The business case under scrutiny in this series revolves round the Conference Organisation Administration (COA). Conference visitors can register for the conference on the website. This registration triggers the backoffice process – by sending an email – crude but effective and still quite common!

 

This website – in this example represented by a static HTML document – allows users to register for the (fictitious) SOA and BPEL Conference.

The HTML Form in this static document posts to some generic servlet, somewhere on the internet:

<form action="http://10.0.0.156:8988/COA_WEB-ViewController-context-root/htmlpost2emailservlet" 
 method="post" enctype="application/x-www-form-urlencoded">
            <input type="hidden" name="email_addressee"
                   value="jellema@amis.nl"/>
            <input type="hidden" name="email_subject"
                   value="Conference Registration"/>
            <input type="hidden" name="email_sender"
                   value="COA-WEB"/>

This Form must contain at least three parameters that are used by the servlet to send an email containing all form values posted by the conference registeree. In this case – my own email address (jellema@amis.nl) is the one to which the email composed from the HTML Form Post is sent.

The servlet processes the Posted Parameters and composes an email that is subsequently sent to the addressee specified in the form. This likely an email account that is monitored by a backoffice clerk, the BPEL process activation agent – or a more simplistic poller – that initiates the back office process.

The email is sent and received by the Back Office.

It contains the values of all parameters in the Registration Form:

HTMLFormPost2EmailServlet

The Servlet taking care of the processing of the HTML Form Post into an email is quite simple. We have the Servlet itself that makes use of an even simpler Emailer Class. Note that functionality was the primary aim of this code – more so than elegant and properly refactored code design.

The servlet:

package nl.amis.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.*;

public class HtmlPost2EmailServlet extends HttpServlet {
    private static final String CONTENT_TYPE = 
        "text/html; charset=windows-1252";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doPost(HttpServletRequest request, 
                       HttpServletResponse response) throws ServletException, 
                                                            IOException {
        String emailAddressee = "";
        String emailSubject = "";
        String emailSender = "";
        String content = "";
        emailAddressee = request.getParameter("email_addressee");
        emailSubject = request.getParameter("email_subject");
        emailSender = request.getParameter("email_sender");

        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String)paramNames.nextElement();
            String paramValue = "";
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                paramValue = paramValues[0];
            } else {
                for (int i = 0; i < paramValues.length; i++) {
                    paramValue = paramValue + (i > 0 ? "," : "") + paramValues[i];
                } // for
            }
            content = content + paramName + "=" + paramValue + "\n";
        } //while


        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head><title>HtmlPost2EmailServlet</title></head>");

        try {
            EmailSender.sendEmail(emailAddressee, emailSubject, emailSender, 
                                  content);
            out.println("<body onload='alert(\"Your registration was received successfully. Thank you! \");'>");
            out.println("The email has been sent. <a href='javascript:history.go(-1);'>Return to previous page.</a> ");
        } catch (Exception e) {
            out.println("<body onload='alert(\"Unfortunately, an error occurred while processing your request! \");'>");
            out.println("Could you please try again. <a href='javascript:history.go(-1);'>Return to previous page.</a> ");

        }

        out.println("</body></html>");
        out.close();
    }
}

The result as presented to the user after posting the registration form:

The Emailer Class:

package nl.amis.util;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class EmailSender {
    public EmailSender() {
    }

    public static void sendEmail( String to, String subject, String from, String content) throws Exception{
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", "mailhost.amis.nl");
        props.setProperty("mail.user", "mail_user");
        props.setProperty("mail.password", "");

        Session mailSession = Session.getDefaultInstance(props, null);
        Transpo
rt transport = mailSession.getTransport(
);

        MimeMessage message = new MimeMessage(mailSession);
        message.addFrom(new Address[] { new InternetAddress("jellema@amis.nl",from)});  // the reply to email address and a logical descriptor of the sender of the email!

        message.setSubject(subject);
        message.setContent(content, "text/plain");
        message.addRecipient(Message.RecipientType.TO,
             new InternetAddress(to));

        transport.connect();
        transport.sendMessage(message,
            message.getRecipients(Message.RecipientType.TO));
        transport.close();
        }
        
        public static void main (String[] args) throws Exception {
            String content = "Some test content.";
            EmailSender.sendEmail("jellema@amis.nl","An interesting message","THE APP",content);
        }
   }

About Post Author

Lucas Jellema

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director and Oracle Developer Champion. Solution architect and developer on diverse areas including SQL, JavaScript, Kubernetes & Docker, Machine Learning, Java, SOA and microservices, events in various shapes and forms and many other things. Author of the Oracle Press book Oracle SOA Suite 12c Handbook. Frequent presenter on user groups and community events and conferences such as JavaOne, Oracle Code, CodeOne, NLJUG JFall and Oracle OpenWorld.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

2 thoughts on “Generic Service – HTML Form Post to Email Servlet

  1. Sam, It is not hugely different, except for a few things:
    – it is supported by all browsers, as it does not rely on the widely varying implementation of the mailto action
    – it creates – depending on the servlet of course – a nicer email message (not just one long line with all data); an enhanced version of the servlet can even create an XML document in the Email body
    – I did not know about the mailto action until you wrote your comment. So thanks for the enlightenment.

    best regards,

    Lucas

Comments are closed.

Next Post

Implementing a stand alone Email Server - Getting Started with Apache James

Using email as a decoupled integration mechanism for applications is a fairly crude and simplistic yet effective approach. Messaging infrastructures – MOM – were all the rage, and still are as part of the ESB architectures and products. The idea is simple: a message sent, it is queued and will […]
%d bloggers like this: