JavaWeb-功能扩展-邮件发送
1.依赖
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
2.以QQ邮箱为例发送简单邮件(纯文本)
打开设置QQ邮箱的邮件服务
后端代码
public class EasyMail {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.host","stmp.qq.com");//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol","smtp");
properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
//QQ邮箱需要SSL加密,
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",sf);
//使用JavaMail 发送邮件的5个步骤
//1.创建定义整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("你的邮箱","授权码");
}
});
//开启Session的debug模式,以查看程序发送邮件的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","你的邮箱","授权码");
//4.创建邮件
//需要传递session
MimeMessage message = new MimeMessage(session);
//发件人
message.setFrom(new InternetAddress("你的邮箱"));
//收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress("收件人邮箱"));
//邮件主题
message.setSubject("easy mail");
//邮件内容
message.setContent("<h1 style='color:red'>hello! I'm testing</h1>","text/html;charset=UTF-8");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
System.out.println("发送成功");
//关闭连接
ts.close();
}
}
3.发送带多媒体(甚至附件)的邮件
public class MixMail {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.host","stmp.qq.com");//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol","smtp");
properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
//QQ邮箱需要SSL加密,
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",sf);
//使用JavaMail 发送邮件的5个步骤
//1.创建定义整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("你的邮箱","授权码");
}
});
//开启Session的debug模式,以查看程序发送邮件的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","你的邮箱","授权码");
//4.创建邮件
//需要传递session
MimeMessage message = new MimeMessage(session);
//发件人
message.setFrom(new InternetAddress("你的邮箱"));
//收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress("对方邮箱"));
//邮件主题
message.setSubject("mix mail");
//准备图片的数据
MimeBodyPart image = new MimeBodyPart();
//图片需要经过数据处理 DataHandler:数据处理
DataHandler dh = new DataHandler(new FileDataSource("E:\\learnJava\\JavaWeb\\FunctionExtension\\mail\\src\\akali.jpg"));
image.setDataHandler(dh);//在body中放入该图片数据
image.setContentID("a.jpg");//给图片ID 便于引用(cid)
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片<img src='cid:a.jpg'>的邮件","text/html;charset=UTF-8");
//附件
MimeBodyPart fj = new MimeBodyPart();
fj.setDataHandler(new DataHandler(new FileDataSource("E:\\learnJava\\JavaWeb\\FunctionExtension\\mail\\src\\db.properties")));
fj.setFileName("db.properties");
//封装
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.addBodyPart(fj);
mm.setSubType("mixed");//mixed>related>text
//保存
message.setContent(mm);
message.saveChanges();
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
System.out.println("发送成功");
//关闭连接
ts.close();
}
}
3.实现注册时发送邮件至用户邮箱
获取前端的邮箱信息,将其和用户名密码等封装发送给后端,并将上面得代码加以改造(将邮箱字符串用封装的变量代替)
前端的界面
index.jsp 注册界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/RegisterServlet.do" method="post">
<P><label for="username">用户名:</label><input type="text" name="username" ></P>
<P><label for="password">密码:</label><input type="text" name="password" ></P>
<P><label for="email">邮箱:</label><input type="text" name="email" ></P>
<p><input type="submit" value="注册"></p>
</form>
</body>
</html>
info.jsp 注册后返回的界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>success</title>
</head>
<body>
<h1 style="color: brown">${message}</h1>
</body>
</html>
后端
这里使用多线程来优化用户的使用体验,不要让浏览器界面等待邮件发送(转圈圈)
实体类User封装用户名,密码,邮箱等信息
public class User implements Serializable {
private String username;
private String password;
private String email;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
SendMail.java 发送邮件的线程类
//多线程提升用户体验
public class SendMail extends Thread{
//给用户发送邮件的邮箱
private String from = "你的邮箱";
//邮箱的用户名
private String username = "你的邮箱";
//密码(授权码)
private String password = "授权码";
//发送邮件的服务器地址
private String host = "smtp.qq.com";
private User user;
public SendMail(User user){
this.user = user;
}
@Override
public void run() {
try {
Properties properties = new Properties();
properties.setProperty("mail.host","stmp.qq.com");//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol","smtp");
properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
//QQ邮箱需要SSL加密,
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",sf);
//使用JavaMail 发送邮件的5个步骤
//1.创建定义整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("你的邮箱","授权码");
}
});
//开启Session的debug模式,以查看程序发送邮件的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect(host,username,password);
//4.创建邮件
//需要传递session
MimeMessage message = new MimeMessage(session);
//发件人
message.setFrom(new InternetAddress(from));
//收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));
//邮件主题
message.setSubject("用户注册邮件");
//邮件内容
String info = "恭喜您注册成功!</br>您的用户名:"+user.getUsername() +"</br>您的密码:"+user.getPassword()+"</br>请妥善保存,如有问题请拨打110";
message.setContent(info,"text/html;charset=UTF-8");
message.saveChanges();
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//关闭连接
ts.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
RegisterServlet.java 接收返回数据,控制页面跳转
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收用户请求,封装成对象
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
User user = new User(username,password,email);
//用户注册成功之后,给用户发送一封邮件
//使用线程专门发送邮件,防止出现转圈圈,和注册人数过多时出现的问题
SendMail send = new SendMail(user);
//启动线程
send.start();
//
req.setAttribute("message","注册成功,我们已经发送了一封带有注册信息的电子邮件,请查收!若网络存在波动,请稍等(●'◡'●)");
req.getRequestDispatcher("info.jsp").forward(req,resp);
}
}