Sending email through JavaMail API in Servlet
The JavaMail API provides many classes that can be used to send email from java. The javax.mail and javax.mail.internet packages contains all the classes required for sending and receiving emails. |
For better understanding of this example click steps for sending email from javamail api |
For sending the email using JavaMail API, you need to load the two jar files:
|
Example of Sending email through JavaMail API in Servlet
Here is the simple example of sending email from servlet. For this example we are creating 3 files:
|
index.html
- <form action="servlet/SendMail">
- To:<input type="text" name="to"/><br/>
- Subject:<input type="text" name="subject"><br/>
- Text:<textarea rows="10" cols="70" name="msg"></textarea><br/>
- <input type="submit" value="send"/>
- </form>
SendMail.java
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class SendMail extends HttpServlet {
- public void doGet(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
- String to=request.getParameter("to");
- String subject=request.getParameter("subject");
- String msg=request.getParameter("msg");
- Mailer.send(to, subject, msg);
- out.print("message has been sent successfully");
- out.close();
- }
- }
Mailer.java
- import java.util.Properties;
- import javax.mail.*;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- public class Mailer {
- public static void send(String to,String subject,String msg){
- final String user="sonoojaiswal@javatpoint.com";//change accordingly
- final String pass="xxxxx";
- //1st step) Get the session object
- Properties props = new Properties();
- props.put("mail.smtp.host", "mail.javatpoint.com");//change accordingly
- props.put("mail.smtp.auth", "true");
- Session session = Session.getDefaultInstance(props,
- new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(user,pass);
- }
- });
- //2nd step)compose message
- try {
- MimeMessage message = new MimeMessage(session);
- message.setFrom(new InternetAddress(user));
- message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
- message.setSubject(subject);
- message.setText(msg);
- //3rd step)send message
- Transport.send(message);
- System.out.println("Done");
- } catch (MessagingException e) {
- throw new RuntimeException(e);
- }
- }
- }