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 sending the email using JavaMail API, you need to load the two jar files:
download these jar files or go to the Oracle site to download the latest version.
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 file for input
- SendMail.java , a servlet file for handling the request and providing the response to the user. It uses the send method of Mailer class to send the email.
- Mailer.java , a java class that contains send method to send the emails to the mentioned recipient.
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";
- final String pass="xxxxx";
-
-
- Properties props = new Properties();
- props.put("mail.smtp.host", "mail.javatpoint.com");
- props.put("mail.smtp.auth", "true");
-
- Session session = Session.getDefaultInstance(props,
- new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(user,pass);
- }
- });
-
- 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);
-
-
- Transport.send(message);
-
- System.out.println("Done");
-
- } catch (MessagingException e) {
- throw new RuntimeException(e);
- }
-
- }
- }
No comments:
Post a Comment