Following is the example to send the mail by using servlet concept.
EmailServlet.java
[java]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);
}
}[/java]
This is the servlet that tries to send the email. The developer will get the necessary parameters from the request.
[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");
[/java]
The properties class is utilized for setup. Notice that developer set the validation property to true.
[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");[/java]
The developer create a
new Authentication class to check the login and the password.
[java] Authenticator auth = new SMTPAuthenticator(login, password);[/java]
The developer create a new mail session.
[java]Session session = Session.getInstance(props, auth);[/java]
The developer set the
text of the message,
subject,
sender and
recipient email addresses.
[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);[/java]
Numerous things may turn out badly, while sending an email. For instance developer may give a wrong email address or the confirmation falls flat. Here we respond to an
AuthenticationFailedException. On the off chance that we get such a special case, we set an ErrorMessage credit to the solicitation and forward to the error.jsp record.
[java]} catch (AuthenticationFailedException ex) {
request.setAttribute("ErrorMessage", "Authentication failed");
RequestDispatcher dispatcher = request.getRequestDispatcher(err);
dispatcher.forward(request, response);
}[/java]
index.jsp
[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 style="background:#80BFFF">
<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>[/java]
Here the developer just created required text boxes to send an email.
success.jsp
[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>[/java]
If the mail is sent successfully message will be printed that is
Email sent.
error.jsp
[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>[/java]
Numerous things may turn out badly, while sending an email. For instance developer may give a wrong email address or the confirmation falls flat. Here we respond to an AuthenticationFailedException. On the off chance that we get such a special case, we set an ErrorMessage credit to the solicitation and forward to the error.jsp record.
web.xml
[xml]<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>mail</servlet-name>
<servlet-class>com.splesson.EmailServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mail</servlet-name>
<url-pattern>/EmailServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>[/xml]
Code will be compiled from the welcome file that is
index.jsp, make sure that servlet name should be same in web.xml.
Output
When compile the program following is the output displayed where user has to enter log in details.
After entering the details click on button then mail will be sent. When click on submit button following message will be displayed
Now check the mail.