Servlet Sending Email
Sending an email using a Servlet is very simple, but first you must install JavaMail API and Java Activation Framework)JAF).
- You can download the latest version from the Java website at JavaMail; on the right side of the web page there is a Downloads link; click it to download.
- You can download the latest version from the Java website at JAF (version 1.1.1).
You can also use the download links provided by this site:
Download and extract these files; in the newly created top-level directory, you will find some jar files for these two applications. You need to add the mail.jar and activation.jar files to your CLASSPATH.
Sending a Simple Email
The following example will send a simple email from your computer. This assumes yourlocalhostis connected to the Internet and supports sending email. Also make sure all the jar files of the Java Email API package and the JAF package are available in the CLASSPATH.
// File 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";
// Sender's email ID
String from = "web@gmail.com";
// Assuming you are sending email from the local host
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Set 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 the 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);
String title = "Sending Email";
String res = "Message sent successfully...";
String docType = " \n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" +
"" + title + "
\n" +
"" + res + "
\n" +
"");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Now let's compile the above Servlet and create the following entry in the web.xml file:
....
SendEmail
SendEmail
SendEmail
/SendEmail
....
Now invoke this Servlet by visiting the URL http://localhost:8080/SendEmail. This will send an email to the given email ID abcd@gmail.com, and the response shown below will be displayed:
Sending EmailMessage sent successfully... |
|---|
If you want to send an email to multiple recipients, use the following method to specify multiple email IDs:
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 carbon copy, and BCC stands for blind carbon copy. For example Message.RecipientType.TO.
- **addresses:** This is an array of email IDs. When specifying email IDs, you need to use the InternetAddress() method.
Sending an HTML Email
The following example will send an HTML-formatted email from your computer. This assumes yourlocalhostis connected to the Internet and supports sending email. Also make sure all the jar files of the Java Email API package and the JAF package are available in the CLASSPATH.
This example is very similar to the previous one, but here we use the setContent() method to set the second parameter to "text/html" content, which specifies that HTML content is contained in the message.
Using this example, you can send HTML content of unlimited size.
// File 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";
// Sender's email ID
String from = "web@gmail.com";
// Assuming you are sending email from the local host
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Set 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 the 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!");
// Set the actual HTML message, content size unlimited
message.setContent("This is actual message
",
"text/html" );
// Send message
Transport.send(message);
String title = "Sending Email";
String res = "Message sent successfully...";
String docType = " \n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" +
"" + title + "
\n" +
"" + res + "
\n" +
"");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Compile and run the Servlet above to send an HTML message to the given e-mail ID.
Sending Attachments in E-mail
The following example sends an e-mail with an attachment from your computer. Here it is assumed that yourlocalhostis connected to the Internet and supports sending email. Also make sure all the jar files of the Java Email API package and the JAF package are available in the CLASSPATH.
// File 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";
// Sender's email ID
String from = "web@gmail.com";
// Assuming you are sending email from the local host
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Set 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 the 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!");
// Create message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill message
messageBodyPart.setText("This is message body");
// Create a multi-part message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is the appendix
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 part
message.setContent(multipart );
// Send message
Transport.send(message);
String title = "Sending Email";
String res = "Email sent successfully...";
String docType = " \n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" +
"" + title + "
\n" +
"" + res + "
\n" +
"");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Compile and run the Servlet above to send a message with a file attachment to the given e-mail ID.
User Authentication Section
If you need to provide a user ID and password to the e-mail server for authentication, you can set the following properties:
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
The rest of the e-mail sending mechanism remains the same as explained above.