package com.j2medev.servletmail;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;
import java.net.*;
public class MailServlet extends HttpServlet
{
private static String host;
private static String from;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
host = config.getInitParameter("host");
from = config.getInitParameter("from");
System.out.println(host + from);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
DataInputStream dis = new DataInputStream(request.getInputStream());
String send = dis.readUTF();
String subject = dis.readUTF();
String content = dis.readUTF();
try
{
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
// Get session
Session session = Session.getDefaultInstance(props, null);
// Define message
MimeMessage message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress(from));
// Set the to address
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
send));
// Set the subject
message.setSubject(subject);
// Set the content
message.setText(content);
// Send message
Transport.send(message);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" ?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>ServletMail</servlet-name>
<servlet-class>com.j2medev.servletmail.MailServlet</servlet-class>
<init-param>
<param-name>host</param-name>
<param-value>smtp.263.net</param-value>
</init-param>
<init-param>
<param-name>from</param-name>
<param-value>eric.zhan@263.net</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletMail</servlet-name>
<url-pattern>/maildo</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>