配置环境 tomcat 10,JDK15,MAVEN 3.6.3
导入jar包
要在网络上实现邮件功能,必须要有专门的邮件服务器。这些邮件服务器类似于现实生活中的邮局,它主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中。
SMTP服务器地址:一般是 smtp.xxx.com,比如163邮箱是smtp.163.com,qq邮箱是smtp.qq.com。
SMTP协议
通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)。
POP3协议
通常把处理用户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)。
以QQ邮箱为例,(仅QQ和阿里邮箱需要密钥)
在QQ邮箱中打开这两个设置 设置-->账户
配置pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>mail</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>15</maven.compiler.source> <maven.compiler.target>15</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> <dependency> <groupId>jakarta.servlet.jsp</groupId> <artifactId>jakarta.servlet.jsp-api</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>5.0.0</version> </dependency> </dependencies> </project>
结构图
User.java
package com.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private String username; private String password; private String email; }
SendOutMail.java
package com.servlet; import com.pojo.User; import com.util.SendMail; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; public class SendOutMail extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理前端请求 String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); //将信息封装进user对象 User user = new User(username, password, email); SendMail sendMail = new SendMail(user); sendMail.start(); //开启线程 request.setAttribute("msg","发送成功"); try { request.getRequestDispatcher("msg.jsp").forward(request,response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
SendMail.java
package com.util; import com.pojo.User; import com.sun.mail.util.MailSSLSocketFactory; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.security.GeneralSecurityException; import java.util.Properties; public class SendMail extends Thread { //发件人信息 private String From = "3220445784@qq.com"; //发件人邮箱 private String recipient = "3220445784@qq.com"; //邮箱密码 private String password = "pdazqsspfpfmdgdc";//QQ的16位密钥 //邮件发送的服务器 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","smtp.qq.com"); properties.setProperty("mail.transport.protocol","smtp"); properties.setProperty("mail.smtp.auth","true"); //QQ存在一个特性设置SSL加密 MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); } catch (GeneralSecurityException e) { e.printStackTrace(); } sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); //创建一个session对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(recipient,password); } }); //开启debug模式 session.setDebug(true); //获取连接对象 Transport transport = null; try { transport = session.getTransport(); } catch (NoSuchProviderException e) { e.printStackTrace(); } //连接服务器 transport.connect(host,From,password); //4、创建邮件,传入session对象 MimeMessage mimeMessage = complexEmail(session); //发送邮件 transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); //关闭连接 transport.close(); }catch (Exception e){ e.printStackTrace(); } } public MimeMessage complexEmail(Session session) throws MessagingException { //创建一个邮件发送对象 MimeMessage mimeMessage = new MimeMessage(session); //邮件发送人 mimeMessage.setFrom(new InternetAddress(recipient)); //邮件接收人 mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); //邮件标题 mimeMessage.setSubject("网站注册成功,赠送图片+附件"); //邮件内容 //准备图片数据 MimeBodyPart image = new MimeBodyPart(); DataHandler handler = new DataHandler(new FileDataSource("C:\\Users\\86183\\Pictures\\Saved Pictures\\25231549-1_e_1.jpg"));//图片地址 image.setDataHandler(handler); image.setContentID("test.png"); //设置图片id //准备文本 MimeBodyPart text = new MimeBodyPart(); text.setContent("网站注册成功,密码为"+user.getPassword()+",请妥善保管密码","text/html;charset=UTF-8"); //附件 MimeBodyPart appendix = new MimeBodyPart(); appendix.setDataHandler(new DataHandler(new FileDataSource("C:\\Users\\86183\\Desktop\\file.txt")));//文件地址 appendix.setFileName("test.txt"); //拼装邮件正文 MimeMultipart mimeMultipart = new MimeMultipart(); mimeMultipart.addBodyPart(image); mimeMultipart.addBodyPart(text); mimeMultipart.setSubType("related");//文本和图片内嵌成功 //将拼装好的正文内容设置为主体 MimeBodyPart contentText = new MimeBodyPart(); contentText.setContent(mimeMultipart); //拼接附件 MimeMultipart allFile = new MimeMultipart(); allFile.addBodyPart(appendix);//附件 allFile.addBodyPart(contentText);//正文 allFile.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed //放到Message消息中 mimeMessage.setContent(allFile); mimeMessage.saveChanges();//保存修改 return mimeMessage; } }
前端显示页面
结构图
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- 注册servlet--> <servlet> <servlet-name>SendOutMail</servlet-name> <servlet-class>com.servlet.SendOutMail</servlet-class> </servlet> <servlet-mapping> <servlet-name>SendOutMail</servlet-name> <url-pattern>/send.do</url-pattern> </servlet-mapping> </web-app>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="${pageContext.request.contextPath}/send.do" method="post"> <p>用户名:<input type="text" name="username" required></p> <p>密码:<input type="password" name="password" required></p> <p>邮箱:<input type="email" name="email" required></p> <p><input type="submit" value="提交"></p> </form> </body> </html>
msg.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${msg} </body> </html>
标签:java,mail,servlet,发送,new,import,com,邮件 From: https://www.cnblogs.com/mo-de/p/16829850.html