Servlet sends email
Sending an email using Servlet is easy, but first you must install JavaMail API and Java Activation Framework) JAF on your computer.
You can download the latest version of the JavaMail open a downloads link on the right side of the page and click on it to download.
You can download the latest version of the JAF(version 1.1.1) .
You can also use the download link provided by this site:
Download and extract these files, and you’ll find some jar files for both applications in the newly created top-level directory. You need to put mail.jar
and activation.jar
files are added to your CLASSPATH
.
Send a simple email
The following example will send a simple email from your computer. It is assumed that your local host is connected to the Internet and supports sending e-mail. At the same time, make sure that all jar files of the Java Email API package and the JAF package are in the CLASSPATH
are all available in.
// file name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Recipient's email ID
String to = "abcd@gmail.com";
// The sender's email ID
String from = "web@gmail.com";
// Assuming you are sending an email from a local host
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Set up mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object
Session session = Session.getDefaultInstance(properties);
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
// Create a default MimeMessage object
MimeMessage message = new MimeMessage(session);
// set up From: header field of the header.
message.setFrom(new InternetAddress(from));
// set up To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// set up Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// send a message
Transport.send(message);
String title = "e-mail sends";
String res = "Successfully sent message...";
String docType = "<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<p align=\"center\">" + res + "</p>\n" +
"</body></html>");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Now let’s compile the Servlet above, and in the web.xml
create the following entries in the file:
....
<servlet>
<servlet-name>SendEmail</servlet-name>
<servlet-class>SendEmail</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SendEmail</servlet-name>
<url-pattern>/SendEmail</url-pattern>
</servlet-mapping>
....
Now call this Servlet by accessing URL http://localhost:8080/SendEmail. Thiswill send an email to the given email ID abcd@gmail.com
and the response shown below is displayed
e-mail sends
Successfully sent message...
If you want to send an email to multiple recipients, use the following method to specify multiple email ID:
void addRecipients(Message.RecipientType type,
Address[] addresses)
throws MessagingException
The following is a description of the parameters:
type
: This will be set to TO, CC, or BCC Here, CC stands for CC and BCC stands for BCC. For exampleMessage.RecipientType.TO
.addresses
: This is an array of e-mail ID When specifying an e-mail ID, you need to use theInternetAddress()
method.
Send an HTML email
The following example sends an email in HTML format from your computer. It is assumed that your local host is connected to the Internet and supports sending e-mail. Also make sure that all jar files for the Java Email API package and the JAF package are available in CLASSPATH.
This example is similar to the previous one, but here we use the setContent()
method to set the content of the second parameter “text/html”, which is used to specify that the HTML content is included inthe message.
Using this example, you can send HTML content of unlimited size.
// file name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Recipient's email ID
String to = "abcd@gmail.com";
// The sender's email ID
String from = "web@gmail.com";
// Assuming you are sending an email from a local host
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Set up mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object
Session session = Session.getDefaultInstance(properties);
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
// Create a default MimeMessage object
MimeMessage message = new MimeMessage(session);
// set up From: header field of the header.
message.setFrom(new InternetAddress(from));
// set up To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// set up Subject: header field
message.setSubject("This is the Subject Line!");
// Set the actual HTML message with unlimited content size
message.setContent("<h1>This is actual message</h1>",
"text/html" );
// send a message
Transport.send(message);
String title = "e-mail sends";
String res = "Successfully sent message...";
String docType = "<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<p align=\"center\">" + res + "</p>\n" +
"</body></html>");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Compile and run the above Servlet to send the HTML message on the given email ID.
Send attachments in email
The following example will send an email with an attachment from your computer. It is assumed that your local host is connected to the Internet and supports sending e-mail. At the same time, make sure that all jar files of the Java Email API package and the JAF package are in the CLASSPATH
are all available in.
// file name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Recipient's email ID
String to = "abcd@gmail.com";
// The sender's email ID
String from = "web@gmail.com";
// Assuming you are sending an email from a local host
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Set up mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object
Session session = Session.getDefaultInstance(properties);
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
// Create a default MimeMessage object
MimeMessage message = new MimeMessage(session);
// set up From: header field of the header.
message.setFrom(new InternetAddress(from));
// set up To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// set up Subject: header field
message.setSubject("This is the Subject Line!");
// Message section
BodyPart messageBodyPart = new MimeBodyPart();
// Fill in message
messageBodyPart.setText("This is message body");
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set Text Message Section
multipart.addBodyPart(messageBodyPart);
// The second part is the 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 section
message.setContent(multipart );
// send a message
Transport.send(message);
String title = "e-mail sends";
String res = "Successfully sent email...";
String docType = "<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<p align=\"center\">" + res + "</p>\n" +
"</body></html>");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Compile and run the above Servlet to send a message with a file attachment on the given e-mail ID.
User identity authentication part
If you need to provide the email server with a user ID and password for authentication, you can set the following properties:
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
The rest of the email sending mechanism is consistent with what was explained above.