Wednesday, 6 April 2016

How to send e-mail using JavaMail APIs ?


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 {
        // set the SMTP host property value
        Properties properties = System.getProperties();
        properties.put("mail.smtp.host", smtpServer);
        // create a JavaMail session
        Session session = Session.getInstance(properties, null);
        // create a new MIME message
        MimeMessage message = new MimeMessage(session);
        // set the from address
        Address fromAddress = new InternetAddress(from);
        message.setFrom(fromAddress);
        // set the to address
        if (to != null) {
           Address[ ]  toAddress = InternetAddress.parse(to);
           message.setRecipients(Message.RecipientType.TO, toAddress);
        } else {
          throw new MessagingException("No \"To\" address specified");
        }
 
         // set the subject
         message.setSubject(subject);
         // set the message body
         message.setText(text);
         // send the message
         Transport.send(message);
         out.println("Message sent successfully.");
     } catch (AddressException e) {
         out.println("Invalid e-mail address.<br>" + e.getMessage());
     } catch (SendFailedException e) {
         out.println("Send failed.<br>" + e.getMessage());
     } catch (MessagingException e) {
         out.println("Unexpected error.<br>" + e.getMessage());
     }
  }
}

No comments:

Post a Comment

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