Java EE Sending email in a Servlet

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
(Новая: <h1>Sending email in a Servlet</h1> In this part of the JEE tutorials we will send an email using a servlet. To work with email, we use the Java Mail API. If we build the example with ...)
(нарушало авторские права)
 
Строка 1: Строка 1:
-
<h1>Sending email in a Servlet</h1>
 
-
In this part of the JEE tutorials we will send an email using a servlet.
 
-
To work with email, we use the Java Mail API. If we build the example with the Netbeans IDE (with the JEE pack), the necessary jars are provided. Otherwise we need to download the mail.jar and the activation.jar files.
 
-
 
-
== Sending email ==
 
-
In the next example we fill in the form and send an email. We use the Java Mail API.
 
-
In order to succeed sending an email, we must have a gmail account. We use the Google's smtp server to forward the email. So in the form, we must provide the login and the password of our gmail account.
 
-
The example consists of five files. A css style file provides the look and feel for our jsp pages.
 
-
The index.jsp is used to fill in the form and send the data to the servlet. The EmailServlet processes the data and tries to send the email to the recipient. If it succeeds, the servlet forwards to the success.jsp file.
 
-
If not, we receive an error message in error.jsp file.
 
-
 
-
<source lang="java">
 
-
* { font-size: 12px; font-family: Verdana }
 
-
 
-
input, textarea { border: 1px solid #ccc }
 
-
textarea { text-align:left}
 
-
table { margin-top: 10% }
 
-
 
-
.error { margin-top: 10%; border: 1px dotted #db1f1f; width: 250px }
 
-
.msg { margin-top: 10%; border: 1px dotted #ccc; width: 250px }
 
-
</source>
 
-
 
-
This is a stylesheet file. The .error class provides a style for the error message. It is a dotted red rectangle.
 
-
The .msg class is used in the success.jsp file. It is a gray dotted rectangle.
 
-
 
-
<source lang="java">
 
-
 
-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
-
 
-
<html>
 
-
<head>
 
-
 
-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
-
<title>Sending email</title>
 
-
<link rel="stylesheet" href="style.css" type="text/css">
 
-
</head>
 
-
<body>
 
-
<center>
 
-
<form action="EmailServlet"> 
 
-
<table>
 
-
 
-
<tr>
 
-
<td>From</td>
 
-
<td><input type="text" name="from"></td>
 
-
</tr>
 
-
<tr>
 
-
<tr>
 
-
<td>To</td>
 
-
 
-
<td><input type="text" name="to"></td>
 
-
</tr>
 
-
<tr>
 
-
<td>Subject</td>
 
-
<td><input type="text" name="subject"></td>
 
-
</tr>   
 
-
 
-
<tr>
 
-
<td>Message</td>
 
-
<td><textarea cols="25" rows="8" name="message"></textarea></td>
 
-
</tr>
 
-
<tr>
 
-
<td>Login</td>
 
-
 
-
<td><input type="text" name="login"></td>
 
-
</tr>
 
-
<tr>
 
-
<td>Password</td>
 
-
<td><input type="password" name="password"></td>
 
-
</tr>
 
-
 
-
</table>
 
-
<br>
 
-
<input type="submit" value="submit">
 
-
</form>
 
-
</center>
 
-
</body>
 
-
</html>
 
-
</source>
 
-
 
-
This is the form for sending the email. There are also inputs for the gmail's login and password.
 
-
 
-
[[image: java_ee_faq_emailform.png| center]]
 
-
 
-
<source lang="java">
 
-
package com.zetcode;
 
-
 
-
import java.io.*;
 
-
import java.net.*;
 
-
 
-
import java.util.Properties;
 
-
import javax.mail.AuthenticationFailedException;
 
-
import javax.mail.Authenticator;
 
-
import javax.mail.PasswordAuthentication;
 
-
import javax.mail.Message;
 
-
import javax.mail.MessagingException;
 
-
import javax.mail.Session;
 
-
import javax.mail.Transport;
 
-
import javax.mail.internet.AddressException;
 
-
import javax.mail.internet.InternetAddress;
 
-
import javax.mail.internet.MimeMessage;
 
-
import javax.servlet.*;
 
-
import javax.servlet.http.*;
 
-
 
-
public class EmailServlet extends HttpServlet {
 
-
 
-
    protected void processRequest(HttpServletRequest request,
 
-
                                  HttpServletResponse response)
 
-
                  throws IOException, ServletException {
 
-
 
-
        final String err = "/error.jsp";
 
-
        final String succ = "/success.jsp";
 
-
 
-
        String from = request.getParameter("from");
 
-
        String to = request.getParameter("to");
 
-
        String subject = request.getParameter("subject");
 
-
        String message = request.getParameter("message");
 
-
        String login = request.getParameter("login");
 
-
        String password = request.getParameter("password");
 
-
 
-
        try {
 
-
            Properties props = new Properties();
 
-
            props.setProperty("mail.host", "smtp.gmail.com");
 
-
            props.setProperty("mail.smtp.port", "587");
 
-
            props.setProperty("mail.smtp.auth", "true");
 
-
            props.setProperty("mail.smtp.starttls.enable", "true");
 
-
 
-
            Authenticator auth = new SMTPAuthenticator(login, password);
 
-
 
-
            Session session = Session.getInstance(props, auth);
 
-
 
-
            MimeMessage msg = new MimeMessage(session);
 
-
            msg.setText(message);
 
-
            msg.setSubject(subject);
 
-
            msg.setFrom(new InternetAddress(from));
 
-
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
 
-
            Transport.send(msg);
 
-
 
-
        } catch (AuthenticationFailedException ex) {
 
-
            request.setAttribute("ErrorMessage", "Authentication failed");
 
-
 
-
            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
 
-
            dispatcher.forward(request, response);
 
-
 
-
        } catch (AddressException ex) {
 
-
            request.setAttribute("ErrorMessage", "Wrong email address");
 
-
 
-
            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
 
-
            dispatcher.forward(request, response);
 
-
 
-
        } catch (MessagingException ex) {
 
-
            request.setAttribute("ErrorMessage", ex.getMessage());
 
-
 
-
            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
 
-
            dispatcher.forward(request, response);
 
-
        }
 
-
            RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
 
-
            dispatcher.forward(request, response);
 
-
 
-
    }
 
-
 
-
    private class SMTPAuthenticator extends Authenticator {
 
-
 
-
        private PasswordAuthentication authentication;
 
-
 
-
        public SMTPAuthenticator(String login, String password) {
 
-
            authentication = new PasswordAuthentication(login, password);
 
-
        }
 
-
 
-
        protected PasswordAuthentication getPasswordAuthentication() {
 
-
            return authentication;
 
-
        }
 
-
    }
 
-
 
-
    protected void doGet(HttpServletRequest request,
 
-
                        HttpServletResponse response)
 
-
                  throws ServletException, IOException {
 
-
        processRequest(request, response);
 
-
    }
 
-
 
-
    protected void doPost(HttpServletRequest request,
 
-
                          HttpServletResponse response)
 
-
                  throws ServletException, IOException {
 
-
        processRequest(request, response);
 
-
    }
 
-
}
 
-
</source>
 
-
 
-
This is the servlet, that tries to send the email.
 
-
 
-
<source lang="java">
 
-
String from = request.getParameter("from");
 
-
String to = request.getParameter("to");
 
-
String subject = request.getParameter("subject");
 
-
String message = request.getParameter("message");
 
-
String login = request.getParameter("login");
 
-
String password = request.getParameter("password");
 
-
</source>
 
-
 
-
We get the necessary parameters from the request.
 
-
 
-
<source lang="java">
 
-
Properties props = new Properties();
 
-
props.setProperty("mail.host", "smtp.gmail.com");
 
-
props.setProperty("mail.smtp.port", "587");
 
-
props.setProperty("mail.smtp.auth", "true");
 
-
props.setProperty("mail.smtp.starttls.enable", "true");
 
-
</source>
 
-
 
-
The properties class is used for configuration. Notice that we set the authentication property to true.
 
-
 
-
<source lang="java">
 
-
Authenticator auth = new SMTPAuthenticator(login, password);
 
-
</source>
 
-
 
-
We create a new <b>Authenticator</b> class to check the login and the password.
 
-
 
-
<source lang="java">
 
-
 
-
Session session = Session.getInstance(props, auth);
 
-
</source>
 
-
 
-
We create a new mail session. We provide the properties and the Authenticator.
 
-
 
-
<source lang="java">
 
-
MimeMessage msg = new MimeMessage(session);
 
-
msg.setText(message);
 
-
msg.setSubject(subject);
 
-
msg.setFrom(new InternetAddress(from));
 
-
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
 
-
Transport.send(msg);
 
-
</source>
 
-
 
-
Here we create a message. We set the text of the message, subject, sender and recipient email addresses. Finally, we send the email message.
 
-
 
-
<source lang="java">
 
-
} catch (AuthenticationFailedException ex) {
 
-
    request.setAttribute("ErrorMessage", "Authentication failed");
 
-
 
-
    RequestDispatcher dispatcher = request.getRequestDispatcher(err);
 
-
    dispatcher.forward(request, response);
 
-
}
 
-
</source>
 
-
 
-
Many things might go wrong, while sending an email. For example we might provide a wrong email address or the authentication fails. Here we react to an <b>AuthenticationFailedException</b>. If we receive such an exception,  we set an ErrorMessage attribute to the request and forward to the error.jsp file. The ErrorMessage attribute will be used in the error.jsp file.
 
-
 
-
<source lang="java">
 
-
 
-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
-
 
-
<html>
 
-
  <head>
 
-
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
-
    <title>Error</title>
 
-
      <link rel="stylesheet" href="style.css" type="text/css">
 
-
    </head>
 
-
 
-
    <body>
 
-
      <center>
 
-
        <div class="error">
 
-
          <h2>Error</h2>
 
-
            <p>
 
-
 
-
              Message: <%= request.getAttribute("ErrorMessage") %>   
 
-
            </p>
 
-
        </div>
 
-
      </center>
 
-
    </body>
 
-
</html>
 
-
 
-
</source>
 
-
 
-
This jsp file will be displayed, when an error occurs. The ErrorMessage attribute, which was set in the servlet, is displayed.
 
-
 
-
<source lang="java">
 
-
 
-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
-
 
-
<html>
 
-
  <head>
 
-
 
-
    <title>Message</title>
 
-
    <link rel="stylesheet" href="style.css" type="text/css">
 
-
  </head>
 
-
  <body>
 
-
    <center>
 
-
 
-
      <div class="msg">
 
-
        <h2>Message</h2>
 
-
          <p>
 
-
              Email sent
 
-
          </p>
 
-
      </div>
 
-
 
-
  </center>
 
-
  </body>
 
-
</html>
 
-
</source>
 
-
 
-
This is the jsp file, which will be displaed, if no errors occured.
 
-
 
-
[[Категория:Java]]
 

Текущая версия на 11:36, 7 апреля 2009