ในการส่งอีเมลโดยใช้ JSP คุณควรมี JavaMail API และ Java Activation Framework (JAF) ติดตั้งบนเครื่องของคุณ
-
คุณสามารถดาวน์โหลด JavaMail เวอร์ชันล่าสุด (เวอร์ชัน 1.2) ได้จากเว็บไซต์มาตรฐานของ Java
-
คุณสามารถดาวน์โหลด JavaBeans Activation Framework JAF เวอร์ชันล่าสุด (เวอร์ชัน 1.0.2) ได้จากเว็บไซต์มาตรฐานของ Java
ดาวน์โหลดและคลายซิปไฟล์เหล่านี้ในไดเร็กทอรีระดับบนสุดที่สร้างขึ้นใหม่ คุณจะพบไฟล์ jar จำนวนหนึ่งสำหรับทั้งสองแอปพลิเคชัน คุณต้องเพิ่ม mail.jar และ activation.jar ไฟล์ใน CLASSPATH ของคุณ
ส่งอีเมลอย่างง่าย
นี่คือตัวอย่างในการส่งอีเมลอย่างง่ายจากเครื่องของคุณ ถือว่า localhost . ของคุณ เชื่อมต่อกับอินเทอร์เน็ตและสามารถส่งอีเมลได้ ตรวจสอบให้แน่ใจว่าไฟล์ jar ทั้งหมดจากแพ็คเกจ Java Email API และแพ็คเกจ JAF มีอยู่ใน CLASSPATH
ตัวอย่าง
<%@ page import = "java.io.*,java.util.*,javax.mail.*"%>
<%@ page import = "javax.mail.internet.*,javax.activation.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%
String result;
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com";
// Sender's email ID needs to be mentioned
String from = "mcmohd@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties object
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session mailSession = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
result = "Sent message successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p align = "center">
<%
out.println("Result: " + result + "\n");
%>
</p>
</body>
</html> ตอนนี้ให้เราใส่โค้ดด้านบนใน SendEmail.jsp ไฟล์และเรียก JSP นี้โดยใช้ URL http"//localhost:8080/SendEmail.jsp . วิธีนี้จะช่วยส่งอีเมลไปยัง ID อีเมลที่ระบุ abcd@gmail.com . คุณจะได้รับคำตอบดังต่อไปนี้ -
ผลลัพธ์
Send Email using JSP Result: Sent message successfully....