นี่คือตัวอย่างในการส่งอีเมล HTML จากเครื่องของคุณ ถือว่า localhost . ของคุณ เชื่อมต่อกับอินเทอร์เน็ตและสามารถส่งอีเมลได้ ตรวจสอบให้แน่ใจว่าไฟล์ jar ทั้งหมดจาก แพ็คเกจ Java Email API และ แพ็คเกจ JAF มีอยู่ใน CLASSPATH
ตัวอย่างนี้คล้ายกับตัวอย่างก่อนหน้านี้มาก ยกเว้นว่าที่นี่เราใช้ setContent() วิธีการตั้งค่าเนื้อหาที่มีอาร์กิวเมนต์ที่สองคือ "text/html" เพื่อระบุว่าเนื้อหา HTML รวมอยู่ในข้อความ
เมื่อใช้ตัวอย่างนี้ คุณสามารถส่งเนื้อหา HTML ขนาดใหญ่เท่าที่คุณต้องการ
ตัวอย่าง
<%@ 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!");
// Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message</h1>", "text/html" );
// Send message
Transport.send(message);
result = "Sent message successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
%>
<html>
<head>
<title>Send HTML 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>