使用JavaMail前,一定要注意:
1.是否开放了 POP3/SMTP服务,并且需要获取授权码
网易邮箱举例
设置中点击POP3/SMTP/IMAP
勾选POP3/SMTP服务
在左边找到客户端授权码,设置一下授权码
2.如果用QQ邮箱,在网易邮箱代码的基础上,还要加上SSL加密(只有QQ才有!)并且创建Session的时候授权码安全验证,其它地方都一样 QQ邮箱发送邮件
3.需要下载两个jar
mail
activation
代码:
首页index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>index</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/mail" method="post">
<p>用户名:<input type="text" name="uname"></p>
<p>密码:<input type="password" name="upassword"></p>
<p>邮箱:<input type="email" name="uemail"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
成功页面success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册成功</title>
<script type="text/javascript">
window.onload = function () {
var time = document.getElementById("time");
var t = 3;
setInterval(function () {
t--;
time.innerText = t;
if(t == 0) {
window.location.href = "${pageContext.request.contextPath}/jsp/index2.jsp";
}
}, 1000);
}
</script>
</head>
<body>
恭喜您注册成功,<span id="time">3</span>秒后跳转...
</body>
</html>
success要跳转的界面index2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>index2</title>
</head>
<body>
hello 这是首页
</body>
</html>
配置文件mail.properties
# 邮件服务器
mail.host=smtp.163.com
# 协议
mail.transport.protocol=smtp
# 是否进行验证
mail.smtp.auth=true
# 发送者
sendUser=song1533968491@163.com
# 授权码
password=song123456
# 发送标题
mail_title=恭喜您,注册成功!
实体类User
package codewen.entity;
import java.io.Serializable;
/**
* @author codewen
*/
public class User implements Serializable {
private String uname;
private String upassword;
private String uemail;
public User() {
}
public User(String uname, String upassword, String uemail) {
this.uname = uname;
this.upassword = upassword;
this.uemail = uemail;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpassword() {
return upassword;
}
public void setUpassword(String upassword) {
this.upassword = upassword;
}
public String getUemail() {
return uemail;
}
public void setUemail(String uemail) {
this.uemail = uemail;
}
@Override
public String toString() {
return "User{" +
"uname='" + uname + '\'' +
", upassword='" + upassword + '\'' +
", uemail='" + uemail + '\'' +
'}';
}
}
编码拦截器EncodingFilter
package codewen.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* @author codewen
*/
@WebFilter(urlPatterns = {"/*"})
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
邮件帮助类MailUtils:如果邮件标题出现中文乱码,参考JavaMail字符编码
package codewen.util;
import codewen.entity.User;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* @author codewen
*/
public class MailUtils implements Runnable{
private User user; //用户
public MailUtils(User user) {
this.user = user;
}
@Override
public void run() {
try {
Properties pro = new Properties();
pro.load(new InputStreamReader(MailUtils.class.getClassLoader().
getResourceAsStream("mail.properties"), "UTF-8"));
//1.创建一个邮箱session会话
Session session = Session.getDefaultInstance(pro);
// 开启session的debug,这样就可以看到邮件发送的运行情况了
session.setDebug(true);
//2.通过session得到transport传输对象
Transport ts = session.getTransport();
//3.通过账户和授权码连接邮箱服务器
//host:邮箱服务器 user:用户名 password:授权码
ts.connect(pro.getProperty("mail.host"), pro.getProperty("sendUser"),
pro.getProperty("password"));
//4.写邮件(创建邮件) 注意传递session
MimeMessage message = new MimeMessage(session); //创建邮件
message.setFrom(new InternetAddress(pro.getProperty("sendUser"))); //指明发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getUemail())); //指明收件人(可以是自己)
String subject = MimeUtility.encodeWord(pro.getProperty("mail_title"), "utf-8", "Q");
message.setSubject(subject); //设置主题
String mail_content = "温馨提示:恭喜您注册成功,您的用户名为"+user.getUname()+",密码为"+user.getUpassword()+"请妥善保管";
message.setContent(mail_content, "text/html;charset=utf-8"); // 设置文本内容
//5.发送邮件
ts.sendMessage(message, message.getAllRecipients());
//6.关闭连接
ts.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
处理邮件的MailServlet:这里使用多线程提高效率!!!非常重要
package codewen.servlet;
import codewen.entity.User;
import codewen.util.MailUtils;
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 java.io.IOException;
/**
* @author codewen
*/
@WebServlet(urlPatterns = {"/servlet/mail"})
public class MailServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uname = req.getParameter("uname");
String upassword = req.getParameter("upassword");
String uemail = req.getParameter("uemail");
User user = new User(uname, upassword, uemail);
MailUtils mail = new MailUtils(user);
new Thread(mail).start(); //开启多线程,提高效率
req.getRequestDispatcher("/jsp/success.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
运行结果:
index.jsp
success.jsp
index2.jsp
网易邮箱: