关闭

servlet+jsp 发送简单邮件

标签: java
143人阅读 评论(0) 收藏 举报

jar包

commons-email-1.4.jar           javax.activation_1.1.0.v201211130549.jar          javax.mail_1.4.0.v201005080615.jar


servlet代码

package com.learn.servlet;


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.SimpleEmail;




public class MailServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
SimpleEmail mail=new SimpleEmail();
mail.setHostName("smtp.sohu.com");
//身份验证
mail.setAuthentication("ppag9133bcfc1107", "jgy15215199133");

try {
//mail.setCharset("utf-8");
mail.addTo(request.getParameter("to"));
mail.setFrom(request.getParameter("from"));
mail.setSubject(request.getParameter("subject"));
mail.setMsg(request.getParameter("body"));
mail.send();
request.getSession().setAttribute("msg", "邮件发送成功");

} catch (Exception e) {
request.getSession().setAttribute("msg", "邮件发送失败");
System.out.println(e.getMessage());
}
request.getRequestDispatcher("result.jsp").forward(request, response);

}

}

jsp内容

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>发送邮件</title>
</head>
<body>
<form action="mail.do" method="post">
收件人:<input type="text" name="to" size="30"><br>
发件人:<input type="text" name="from" size="30"><br>
主题:<input type="text" name="subject" size="30"><br>
正文:<textarea rows="15" cols="50" name="body"></textarea><br>
<input type="submit" value="提交">

</form>
</body>



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2777次
    • 积分:129
    • 等级:
    • 排名:千里之外
    • 原创:10篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档