Sending an email using a Servlet is very simple, but first you must install JavaMail API and Java Activation Framework)JAF)# on your computer ##.
- You can download the latest version of JavaMail (version 1.2) from the Java Standards website.
- You can download the latest version of JAF (version 1.1.1) from the Java Standards website.
Download and unzip these files, and in the newly created top-level directory you will find some jar files for both applications. You need to add the
mail.jar and activation.jar files to your CLASSPATH.
Send a simple emailThe example below will send a simple email from your computer. This assumes that your
localhost is connected to the Internet and supports sending emails. Also ensure that all jar files of the Java Email API package and JAF package are available in CLASSPATH.
// 文件名 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
{
// 收件人的电子邮件 ID
String to = "abcd@gmail.com";
// 发件人的电子邮件 ID
String from = "web@gmail.com";
// 假设您是从本地主机发送电子邮件
String host = "localhost";
// 获取系统的属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
// 获取默认的 Session 对象
Session session = Session.getDefaultInstance(properties);
// 设置响应内容类型
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
// 创建一个默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// 设置 From: header field of the header.
message.setFrom(new InternetAddress(from));
// 设置 To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// 设置 Subject: header field
message.setSubject("This is the Subject Line!");
// 现在设置实际消息
message.setText("This is actual message");
// 发送消息
Transport.send(message);
String title = "发送电子邮件";
String res = "成功发送消息...";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\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 us 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 call this by accessing the URL http://localhost:8080/SendEmail Servlets. This will send an email to the given email id
abcd@gmail.com and will display the response as shown below:
Send EmailMessage successfully sent... |
If you want to send an email to multiple recipients, then use the following method to specify multiple email IDs:
void addRecipients(Message.RecipientType type,
Address[] addresses)
throws MessagingException
Here is the 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 example below will send an HTML formatted email from your computer. This assumes that your localhost is connected to the Internet and supports sending emails. Also ensure that all jar files of the Java Email API package and JAF package are available in CLASSPATH.
This example is very similar to the previous one, but here we use the setContent() method to set the content of the second parameter to "text/html". This parameter is used to specify that the HTML content is included in the message. of.
Using this instance, you can send HTML content with any content size.
// 文件名 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
{
// 收件人的电子邮件 ID
String to = "abcd@gmail.com";
// 发件人的电子邮件 ID
String from = "web@gmail.com";
// 假设您是从本地主机发送电子邮件
String host = "localhost";
// 获取系统的属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
// 获取默认的 Session 对象
Session session = Session.getDefaultInstance(properties);
// 设置响应内容类型
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
// 创建一个默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// 设置 From: header field of the header.
message.setFrom(new InternetAddress(from));
// 设置 To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// 设置 Subject: header field
message.setSubject("This is the Subject Line!");
// 设置实际的 HTML 消息,内容大小不限
message.setContent("<h1>This is actual message</h1>",
"text/html" );
// 发送消息
Transport.send(message);
String title = "发送电子邮件";
String res = "成功发送消息...";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\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 an HTML message on the given email ID.
The example below will send an email with an attachment from your computer. This assumes that your localhost is connected to the Internet and supports sending emails. Also ensure that all jar files of the Java Email API package and JAF package are available in CLASSPATH.
// 文件名 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
{
// 收件人的电子邮件 ID
String to = "abcd@gmail.com";
// 发件人的电子邮件 ID
String from = "web@gmail.com";
// 假设您是从本地主机发送电子邮件
String host = "localhost";
// 获取系统的属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
// 获取默认的 Session 对象
Session session = Session.getDefaultInstance(properties);
// 设置响应内容类型
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
// 创建一个默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// 设置 From: header field of the header.
message.setFrom(new InternetAddress(from));
// 设置 To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// 设置 Subject: header field
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 = "发送电子邮件";
String res = "成功发送电子邮件...";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\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 file attachment on the given email ID.
If you need to provide a user ID and password to the email server for authentication, then you can set the following properties:
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
Email sending mechanism The rest remains the same as explained above.