Wednesday, 6 April 2016

How to send e-mail using SmtpClient class ?


public class SendMailServlet extends HttpServlet {
    String smtpServer;

    public void init(ServletConfig config) throws ServletException {
        // get the SMTP server from the servlet properties
        smtpServer = config.getInitParameter("smtpServer");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
       throws ServletException,   IOException  {
        // get the message parameters from the HTML page
        String from = req.getParameter("from");
        String to = req.getParameter("to");
        String subject = req.getParameter("subject");
        String text = req.getParameter("text");

        PrintWriter out = res.getWriter();
        res.setContentType("text/html");

        try {
            // create an SMTP client
            SmtpClient smtp = new SmtpClient(smtpServer);
            // set the from and to fields
            smtp.from(from);
            smtp.to(to);

            // Get the print stream
            PrintStream message = smtp.startMessage();
            // write the message to the print stream
            message.println("From: " + from);
            message.println("To: " + to);
            message.println("Subject: " + subject);
            message.println(text);
            // close the SMTP connection and send the message
            smtp.closeServer();
            out.println("Message sent successfully.");
        }
        catch (IOException e) {
            out.println("Unexpected error.<br>" + e.getMessage());
        }
    }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.