Search code examples
javaservletsnetbeansjava-web-start

How to convert the content of email message in html format in JSP, Servlet aplication?


I'm working in a project that necessite send email. Emails are already being sent, but I need to implement a more professional format and, from what I've researched, I can implement an HTML format to email. This is necessary because I have to put information related to the project company (image corporate). I tried using msg.SendContent but it didn't work for me. I hope you can guide me.

I'm using NetBeans with the javax.mail library:

public class EmailServicio {

    public static void enviarEmail(String host, String port,
            final String user, final String pass, String destinatario,
            String asunto, String mensaje) throws AddressException,
            MessagingException {

        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pass);
            }
        };

        Session session = Session.getInstance(properties, auth);

        // creates a new e-mail message
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(user));
        InternetAddress[] toAddresses = {new InternetAddress(destinatario)};
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(asunto);
        msg.setContent("<h1>Maipo Grande, lider en exportación</h1>", "text/html");
        msg.setSentDate(new Date());
        msg.setText(mensaje);

        // sends the e-mail
        Transport.send(msg);
    }
}

Servlet Code:

public class ServletContacto extends HttpServlet {

    private String host;
    private String port;
    private String user;
    private String pass;

    public void init() {
        // reads SMTP server setting from web.xml file
        ServletContext context = getServletContext();
        host = context.getInitParameter("host");
        port = context.getInitParameter("port");
        user = context.getInitParameter("user");
        pass = context.getInitParameter("pass");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        UsuarioServicio usua = new UsuarioServicio();
        String url = request.getRequestURI();

        if ("/maipoGrande/Contacto".equals(url)) {
            request.setAttribute("titulo", "Formulario Contacto");
            HttpSession session = request.getSession(true);
            if (session.getAttribute("usuario") == null) {
                response.sendRedirect(request.getContextPath() + "/Login");
            } else {
                getServletContext().getRequestDispatcher("/contacto.jsp").forward(request, response);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String url = request.getRequestURI();
        if ("/maipoGrande/Contacto".equals(url)) {
            String destinatario = "atencion.maipogrande@gmail.com";
            String asunto = request.getParameter("txtAsunto");
            String mensaje = request.getParameter("txtMensaje");
            String mensajeRespuesta = "";
            try {
                EmailServicio.enviarEmail(host, port, user, pass, destinatario, asunto,
                        mensaje);
                mensajeRespuesta = "Su correo fue enviado exitosamente";
            } catch (Exception ex) {
                ex.printStackTrace();
                mensajeRespuesta = "Se ha encontrado un error: " + ex.getMessage();
            } finally {
                request.setAttribute("Mensaje", mensajeRespuesta);
                getServletContext().getRequestDispatcher("/resultado.jsp").forward(
                        request, response);
            }
        }
    }
}

I hope that the h1 (test) is displayed in the message sent.


Solution

  • Although you haven't stated exactly what your problem is, it may be that you are calling msg.setText(mensaje); after calling msg.setContent("<h1>Maipo Grande, lider en exportación</h1>", "text/html");.

    Your call to msg.setContent() will set the MIME type to "text/html", which is what you want. But the subsequent call to msg.setText() will reset the MIME type to "text/plain", which is not what you want when sending an HTML email..

    The solution is simply to remove the call to msg.setText(). Then you will be sending an HTML email. Of course you will also need to amend the content of the message passed to msg.setContent() for your application's email, but that is just an implementation detail.

    See the Javadoc for the interface javax.mail.Part, which is implemented by class javax.mail.Message, for more information on setContent() and setText().

    One other related point is that it looks like your EmailServicio.enviarEmail() method is almost a direct copy of the main() method of class SendHTMLEmail in the tutorial "JavaMail API - Sending an HTML Email", apart from the call to setText() that you added.

    It's worth verifying that you can successfully run your implementation of their simple Java application first. It is much easier to debug a Java application than a servlet if there are any issues to be resolved. Once you have the HTML email application working you can then port your working code over to the web application.