JSP send email


Although it is very simple to use JSP to send emails, it requires JavaMail API and JavaBean Activation Framework.

  • Download the latest version of JavaMail here.

  • Download the latest version of JavaBeans Activation Framework (JAF) here.

Download and unzip these files. In the root directory, you will see a series of jar packages. Add the mail.jar package and activation.jar package to the CLASSPATH variable.

Send a simple email

This example shows how to send a simple email from your machine. It assumes that localhost is connected to the network and has the ability to send an email. At the same time, please confirm again that the mail.jar package and activation.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 = "abcd@gmail.com";

   // 发件人的电子邮件
   String from = "mcmohd@gmail.com";

   // 假设你是从本地主机发送电子邮件
   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 visit http://localhost:8080/SendEmail.jsp, it will send an email to abcd@gmail.com and display the following results:

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

If you want to To send an email to multiple people, the methods listed below can be used to specify multiple email addresses:

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

The description of the parameters is as follows:

  • type: This value will be set to TO, CC, or BCC. CC stands for copy, BCC stands for black copy, and TO is used in the example program.

  • addresses: This is an array of email addresses. When specifying an email address, you need to use the InternetAddress() method.


Send an HTML email

This example sends a simple HTML email. It assumes that your localhost is connected to the network and has the ability to send mail. At the same time, please confirm again that the mail.jar package and activation.jar package have been added to the CLASSPATH variable.

This example is very similar to the previous example, but in this example we use the setContent() method and pass "text/html" as the 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 = "abcd@gmail.com";

   // 发件人的电子邮件
   String from = "mcmohd@gmail.com";

   // 假设你是从本地主机发送电子邮件
   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 to use the above JSP file to send HTML message to email.


Including attachments in emails

This example shows us how to send an email containing 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 = "abcd@gmail.com";

   // 发件人的电子邮件
   String from = "mcmohd@gmail.com";

   // 假设你是从本地主机发送电子邮件
   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>

User authentication section

If the mail server requires a user name and password for user authentication, it can be set as follows:

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

Send an email using a form

Use an HTML form to receive an email and obtain all email 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 obtaining the above information, you can use the example mentioned earlier to send Email.