How to send mail using java jsp



1.  At first download java mail.jar and activation.jar.
You can download from here mail & activation jar file.

2. Now add this two jar in your project lib folder
3. Now take a jsp file and paste this code..
4. Now run the project...
5. Enjoy


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP JavaMail Example </title>
</head>
<body>
<%@ page import="java.util.*" %>
<%@ page import="javax.mail.*" %>
<%@ page import="javax.mail.internet.*" %>
<%@ page import="javax.activation.*" %>
<%

    // Alamgir Hossain, CSE , JUST
    String host = "gmail-smtp-in.l.google.com";
    String to = "malamgirhossain1996@gmail.com";// To mail
    String from = "alamgir.cse14.just@gmail.com";//From mail
    String subject = "Sending Mail check";
    String messageText = "Thanks for attending with us. Md. Alamgir Hossain, Dept. of Computer Science & Engineering. Jessore University of Science & Technology";
    boolean sessionDebug = false;
    // Create some properties and get the default Session.
    Properties props = System.getProperties();
    props.put("mail.host", host);
    props.put("mail.transport.protocol", "smtp");
    Session mailSession = Session.getDefaultInstance(props, null);
    
    // Set debug on the Session
    // Passing false will not echo debug info, and passing True will.
    
    mailSession.setDebug(sessionDebug);
    
    // Instantiate a new MimeMessage and fill it with the
    // required information.
    
    Message msg = new MimeMessage(mailSession);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setText(messageText);
    
    // Hand the message to the default transport service
    // for delivery.
    
    Transport.send(msg);
    out.println("Mail was sent to " + to);
    out.println(" from " + from);
    out.println(" using host " + host + ".");
%>
</body>
</html>

No comments:

Post a Comment