邮件发送

jsp代码:

<%@ page language=”java” contentType=”text/html; charset=utf-8″
    pageEncoding=”utf-8″%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>Insert title here</title>
</head>
<body>
<form action=”/MailTest/mail” method=”post”>
邮件主题<input type=”text” name=”theme”></input>
邮件内容<input type=”text” name=”content”></input>
<br>附件<input type=”file” name=”file” />
<input type=”submit” value=”发送”/>
</form>
</body>
</html>

servlet代码:

import java.io.File;
import java.io.IOException;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.mail.AttachBean;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;
@WebServlet(“/mail”)
public class mail extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding(“utf-8”);
String theme = request.getParameter(“theme”);
String content = request.getParameter(“content”);
String file = request.getParameter(“file”);
System.out.println(file);
Session session = MailUtils.createSession(“smtp.163.com”, “发件人163邮箱帐号”, “邮箱密码”);
Mail mail = new Mail(“发件人的163邮箱”,”收件人的163邮箱”,theme,content);
AttachBean ab1 = new AttachBean(new File(file),file);
mail.addAttach(ab1);
try {
MailUtils.send(session, mail);
response.sendRedirect(“Mail.jsp”);
} catch (MessagingException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注