JSP "Send Email"
Although implementing email sending functionality using JSP is simple, it requires the JavaMail API and the JavaBean Activation Framework to be installed.
You can download the latest version of JavaMail from the Java website. On the right side of the page, there is a Downloads link; click it to download.
You can download the latest version of JAF (Version 1.1.1) from the Java website.
Alternatively, you can use the download links provided on this site:
Download and unzip these files. In the root directory, you will find a series of JAR files. Add the mail.jar and activation.jar files to the CLASSPATH variable.
Sending a Simple Email
This example demonstrates how to send a simple email from your machine. It assumes that localhost is connected to the network and capable of sending an email. Also, ensure that the mail.jar and activation.jar files 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;
// Recipient's email ID
String to = "[email protected]";
// Sender's email ID
String from = "[email protected]";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
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>
This is an example of sending an email using JSP. Accessing http://localhost:8080/SendEmail.jsp will send an email to [email protected] and display the following result:
Send Email using JSP Result: Sent message successfully....
If you want to send the email to multiple recipients, the following method can be used to specify multiple email addresses:
void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException
Parameter descriptions are as follows:
- type: This value will be set to TO (primary recipient), CC (carbon copy), or BCC (blind carbon copy). In the example program, TO is used.
- addresses: This is an array of email addresses, and the InternetAddress() method is required when specifying the addresses.
---
## Sending an HTML Email
This example sends a simple HTML email. It assumes that your localhost is connected to the network and capable of sending emails. Also, ensure that the mail.jar and activation.jar files are included in your CLASSPATH variable.
This example is very similar to the previous one, but in this case, we use the setContent() method, passing "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; // Recipient's email ID String to = "[email protected]";
// Sender's email ID String from = "[email protected]";
// Assuming you are sending email from localhost String host = "localhost";
// Get system properties 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 the From: header field of the header. message.setFrom(new InternetAddress(from)); // Set the To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set the Subject: header field message.setSubject("This is the Subject Line!");
// Send the HTML message
message.setContent("<h1>This is actual message</h1>",
"text/html" );
// Send message
Transport.send(message);
result = "Sent message successfully....";
}catch (MessagingException mex) { mex.printStackTrace();
<% String 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 an HTML message email.
---
## Including Attachments in the Email
This example shows us how to send an email that includes an attachment.
<%@ 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 String to = "[email protected]";
// Sender's email ID String from = "[email protected]";
// Assuming you are sending email from localhost String host = "localhost";
// Get system properties 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 the From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set the To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set the Subject: header field
message.setSubject("This is the Subject Line!");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart );
// Send message
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 Attachment Email using JSP</title> </head> <body> <center> <h1>Send Attachment 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 username and password for user authentication, you can set it up like this:
properties.setProperty("mail.user", "myuser"); properties.setProperty("mail.password", "mypwd");
---
## Sending Email Using a Form
Use an HTML form to receive an email and get all the 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 previously mentioned example to send the email.