Apache的commons-email对JavaMail类进行了封装。用起来十分方便。
到 Apache 官方网站下载org.apache.commons.mail的包http://www.apache.org/下的
Commons项目中下载Email里的commons-email-1.2-bin.zip,将commons-email-1.2.jar引入到工
程中
下面是我写的一个简单的小例子,已经经过测试(这里写了一个Servelet,邮件的内容从一个Jsp页面获得):
JSP代码:
<%@ page pageEncoding="UTF-8" %>
<%@ page contentType="text/html; charset=UTF-8"%>
<%request.setCharacterEncoding("UTF-8");%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<p align="center">发送邮件的程序</p>
<form id="form1" name="form1" method="post" action="sendMail">
<table width="516" height="253" border="0" align="center">
<tr>
<td>收件人:</td>
<td><label>
<input type="text" name="to" id="to" />
</label></td>
</tr>
<tr>
<td>发件人:</td>
<td><label>
<input type="text" name="from" id="from" />
</label></td>
</tr>
<tr>
<td>主题:</td>
<td><label>
<input type="text" name="subject" id="subject" />
</label></td>
</tr>
<tr>
<td>内容:</td>
<td><label>
<textarea name="content" id="content" cols="45" rows="8"></
textarea>
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="button" id="button" value="提交" />
</label></td>
<td><label>
<input type="reset" name="button2" id="button2" value="重置" />
</label></td>
</tr>
</table>
</form>
<p align="center"> </p>
<p> </p>
</body>
</html>
Servelet代码:
package a;
/**
* commons-email实现简单邮件发送
*/
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
public class sendmail extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse
resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
SimpleEmail email=new SimpleEmail(); //简单邮件
email.setHostName("
smtp.sina.com"); //设置smtp服务器地址
email.setAuthentication("sanssxiaonei", "×××××××"); //验证——用户
名,密码
email.setCharset("UTF-8"); //邮件内容的编码
try {
email.setFrom(req.getParameter("from")); //从表单读取发件人
email.addTo(req.getParameter("to")); //从表单读取收件人
email.setSubject(req.getParameter("subject")); //主题
email.setMsg(req.getParameter("content")); //内容
email.send(); //发送
req.setAttribute("sendmail.message", "成功");
} catch (EmailException ex) {
ex.printStackTrace();
req.setAttribute("sendmail.message", "失败");
}
req.getRequestDispatcher("/result.jsp").forward(req,
resp); //转到结果页面
}
}