Simple explained example for sending email via JSP
As like in PHP and other languages emails too can
be sent through JSP .
For sending email in JSP you must have JavaMail API and Java Activation
Framework (JAF) installed in your machine. Now when you have installed these framework I have an example below that could be useful for you to send email from JSP.
First create an HTML Document ,
HTML Document (index.html)
HTML Document (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Nirajanghimireyworkshop.blogspot.com- Sending Mail</title>
</head>
<body>
<form action="link.jsp" method="post">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td>To:</td>
<td>
<input type="text" name="to" size="30" maxlength="30">
</td>
</tr>
<tr>
<td>From:</td>
<td>
<input type="text" name="from" size="30" maxlength="30">
</td>
</tr>
<tr>
<td>Subject</td>
<td>
<input type="text" name="subject" size="30" maxlength="30">
</td>
</tr>
<tr>
<td colspan="2">
<textarea cols="40" rows="10" name="body"></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Submit">
<input type="Reset">
</td>
</tr>
</table>
</form>
</body>
</html>
The above file is skeleton for interface to send email using JSP main fnctions and workings are done throught the below file.
JSP File
(link.jsp)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Nirajanghimireyworkshop.blogspot.com-JSP Mail Sending</title>
</head>
<body>
<%@ page import="java.util.*" %>
<%@ page import="javax.mail.*" %>
<%@ page import="javax.mail.internet.*" %>
<%@ page import="javax.activation.*" %>
<%
String host = "localhost";
String to = request.getParameter("to");
String from = request.getParameter("from");
String subject = request.getParameter("subject");
String messageText = request.getParameter("body");
booleansessionDebug = false;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
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);
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