Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JSP sends a message


May 12, 2021 JSP


Table of contents


JSP sends a message

Although using JSP to implement messaging is simple, you need the JavaMail API and you need to install the JavaBean Activation Framework.

Download and unzip these files, and under the root, you'll see a series of jar packages. Add the .jar package and the .jar package to the CLASSPATH variable.

Send a simple message

This example shows how to send a simple message from your machine. I t assumes that localhost is connected to the network and has the ability to send an e-mail message. In the meantime, make sure .jar mail package and .jar package have been added to the CLASSPATH variable.

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%    
String result;    
// 收件人的电子邮件    
String to = "[email protected]";     
// 发件人的电子邮件    
String from = "[email protected]";     
// 假设你是从本地主机发送电子邮件    
String host = "localhost";     
// 获取系统属性对象    
Properties properties = System.getProperties();     
// 设置邮件服务器    
properties.setProperty("mail.smtp.host", host);     
// 获取默认的Session对象。    
Session mailSession = Session.getDefaultInstance(properties);     
try{       
// 创建一个默认的MimeMessage对象。       
MimeMessage message = new MimeMessage(mailSession);       
// 设置 From: 头部的header字段       
message.setFrom(new InternetAddress(from));       
// 设置 To: 头部的header字段       
message.addRecipient(Message.RecipientType.TO,                                
new InternetAddress(to));       
// 设置 Subject: header字段       
message.setSubject("This is the Subject Line!");       
// 现在设置的实际消息       
message.setText("This is actual 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>

Now access http://localhost:8080/SendEmail.jsp, it will send an email to the [email protected] and display the following results:

Send Email using JSP
Result: Sent message successfully....

If you want to send a message to more than one person, the methods listed below can be used to indicate multiple email addresses:

void addRecipients(Message.RecipientType type, 
                   Address[] addresses)
throws MessagingException

The parameters are described as follows:

  • Type: This value will be set to TO, CC, or BCC. CC stands for copy, BCC stands for black copy, and example program uses TO.
  • Addresses: This is an array of e-mail addresses that need to use the InternetAddress() method when specifying an e-mail address.

Send an HTML message

This example sends a simple HTML message. I t assumes that your localhost is connected to the network and has the ability to send mail. In the meantime, make sure .jar mail package and .jar package have been added to the CLASSPATH variable.

This example is very similar to the previous one, but in this example we used the setContent() method to pass "text/html" to it as a second parameter to indicate that the message contains HTML content.

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%    
String result;    
// 收件人的电子邮件    
String to = "[email protected]";     
// 发件人的电子邮件    
String from = "[email protected]";     
// 假设你是从本地主机发送电子邮件    
String host = "localhost";     
// 获取系统属性对象    
Properties properties = System.getProperties();     
// 设置邮件服务器    
properties.setProperty("mail.smtp.host", host);     
// 获取默认的Session对象。    
Session mailSession = Session.getDefaultInstance(properties);     
try{       // 创建一个默认的MimeMessage对象。       
MimeMessage message = new MimeMessage(mailSession);       
// 设置 From: 头部的header字段       
message.setFrom(new InternetAddress(from));       
// 设置 To: 头部的header字段       
message.addRecipient(Message.RecipientType.TO,                                
new InternetAddress(to));       
// 设置 Subject: header字段       
message.setSubject("This is the Subject Line!");             
// 设置 HTML消息       
message.setContent("<h1>This is actual message</h1>","text/html" );
      // 发送消息
      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>

Now you can try using the JSP file above to send HTML messages to e-mail messages.


Include attachments in the message

This example tells us how to send a message with attachments.

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%    String result;    
// 收件人的电子邮件    
String to = "[email protected]";     
// 发件人的电子邮件    
String from = "[email protected]";     
// 假设你是从本地主机发送电子邮件    
String host = "localhost";     
// 获取系统属性对象    
Properties properties = System.getProperties();     
// 设置邮件服务器    
properties.setProperty("mail.smtp.host", host);     
// 获取默认的Session对象。    
Session mailSession = Session.getDefaultInstance(properties);     
try{       
// 创建一个默认的MimeMessage对象。       
MimeMessage message = new MimeMessage(mailSession);        
// 设置 From: 头部的header字段       
message.setFrom(new InternetAddress(from));        
// 设置 To: 头部的header字段       
message.addRecipient(Message.RecipientType.TO,                                
new InternetAddress(to));       
 // 设置 Subject: header字段       
message.setSubject("This is the Subject Line!");        
// 创建消息部分       
BodyPart messageBodyPart = new MimeBodyPart();        
// 填充消息       
messageBodyPart.setText("This is message body");              
// 创建多媒体消息       
Multipart multipart = new MimeMultipart();        
// 设置文本消息部分       
multipart.addBodyPart(messageBodyPart);        
// 附件部分       
messageBodyPart = new MimeBodyPart();       
String filename = "file.txt";       
DataSource source = new FileDataSource(filename);       
messageBodyPart.setDataHandler(new DataHandler(source));       
messageBodyPart.setFileName(filename);       
multipart.addBodyPart(messageBodyPart);        
// 发送完整消息       
message.setContent(multipart );        
// 发送消息       
Transport.send(message);       
String title = "Send Email";       
result = "Sent message successfully....";    
}catch (MessagingException mex) {       
mex.printStackTrace();       
result = "Error: unable to send message....";    
} 
%>
<html>
<head>
<title>Send Attachement Email using JSP</title>
</head>
<body>
<center>
<h1>Send Attachement Email using JSP</h1>
</center>
<p align="center">
<%     out.println("Result: " + result + "\n"); %>
</p>
</body>
</html>

The user authentication section

If the mail server requires a username and password for user authentication, you can set it up like this:

 props.setProperty("mail.user", "myuser");
 props.setProperty("mail.password", "mypwd");

Use the form to send a message

Use the HTML form to receive a message and get all the message information through the request object:

String to = request.getParameter("to");
String from = request.getParameter("from");
String subject = request.getParameter("subject");
String messageText = request.getParameter("body");

After you get the above information, you can use the example mentioned earlier to send the message.