English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
It is very simple to send an email using Servlet, but first you must install JavaMail API and Java Activation Framework (JAF)。
You can download the latest version of Java from the Java website: JavaMail, there is a button on the right side of the webpage Downloads link, click on it to download.
You can download the latest version of Java from the Java website: JAF (version)} 1.1.1)。
You can also use the download link provided on this site:
Download and unzip these files, and in the newly created top-level directory, you will find some jar files of these applications. You need to add mail.jar and activation.jar file is added to your CLASSPATH.
The following example will send a simple email from your computer. Assuming that yourLocal hostConnected to the internet and supports sending emails. Ensure that all the jar files of the Java Email API and JAF package are available in the CLASSPATH.
// 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 = "[email protected]"; // Sender's email ID String from = "[email protected]"; // Assuming you are sending an email from the local host String host = "localhost"; // Get the system properties Properties properties = System.getProperties(); // Set the email server properties.setProperty("mail.smtp.host", host); // Get the default Session object Session session = Session.getDefaultInstance(properties); // Set the 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 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 = "Send Email"; String res = "Message sent successfully..."; 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> } mex.printStackTrace(); } } }
Now let's compile the above Servlet and create the following entry in the web.xml 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 access the URL http://localhost:8080/Call this Servlet by using SendEmail. This will send an email to the given email ID [email protected],and the response shown below will be displayed:
Send emailMessage sent successfully... |
If you want to send an email to multiple recipients, please 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 an email ID, you need to use the InternetAddress() method.
The following example will send an HTML formatted email from your computer. Assuming that yourLocal hostConnected to the internet and supports sending emails. Ensure that all the jar files of the Java Email API and JAF package are available in the CLASSPATH.
This example is very similar to the previous example, but here we use the setContent() method to set the second parameter to "text"/The content of "html", this parameter is used to specify that the HTML content is included in the message.
With 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 = "[email protected]"; // Sender's email ID String from = "[email protected]"; // Assuming you are sending an email from the local host String host = "localhost"; // Get the system properties Properties properties = System.getProperties(); // Set the email server properties.setProperty("mail.smtp.host", host); // Get the default Session object Session session = Session.getDefaultInstance(properties); // Set the 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 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 is unlimited message.setContent("<h1>This is actual message</h1> "text/html" ); // Send message Transport.send(message); String title = "Send Email"; String res = "Message sent successfully..."; 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> } mex.printStackTrace(); } } }
Compile and run the above Servlet to send an HTML message to the given email ID.
The following example will send an email with an attachment from your computer. Here it is assumed that yourLocal hostConnected to the internet and supports sending emails. Ensure that all the jar files of the Java Email API and JAF package are available in the CLASSPATH.
// 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 = "[email protected]"; // Sender's email ID String from = "[email protected]"; // Assuming you are sending an email from the local host String host = "localhost"; // Get the system properties Properties properties = System.getProperties(); // Set the email server properties.setProperty("mail.smtp.host", host); // Get the default Session object Session session = Session.getDefaultInstance(properties); // Set the 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 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 a message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill in the message messageBodyPart.setText("This is message body"); // Create a multipart message Multipart multipart = new MimeMultipart(); // Set the text message part multipart.addBodyPart(messageBodyPart); // The second part is an 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 part message.setContent(multipart ); // Send message Transport.send(message); String title = "Send Email"; String res = "Email sent successfully..."; 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> } mex.printStackTrace(); } } }
Compile and run the above Servlet to send a message with a file attachment to the given email ID.
If you need to provide a user ID and password for authentication to the email server, you can set the following properties:
props.setProperty("mail.user", "myuser"); props.setProperty("mail.password", "mypwd");
The rest of the email sending mechanism remains consistent with the above explanation.