JavaWeb功能扩展
1.文件上传
【文件上传的注意事项】
- 为保证服务器安全,上传文件应该放在外界无法直接访问的目录下,比如WEB-INF目录下
- 为防止文件覆盖的现象发生,要为上传的文件长生一个唯一的文件名
- 要限制上传文件的最大值
- 可以限制上传文件的类型,在收到上传文件名是,判断后缀名是否合法
1.1依赖包
处理上传的文件,一般都需要通过流来获取,我们可以使用request.getInputStream(),原生态的文件上传流获取,十分麻烦
但是我们建议使用Apache的文件上传组件来实现,common-fileupload,它现需要依赖于commons-io组件
1.2index.jsp
<%--通过表单上传
get:上传文件大小有限制 4kb
post:上传文件大小无限制
--%>
<form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
上传用户:<input type="text" name="username"><br>
<p><input type="file" name="file1"></p>
<p><input type="file" name="file2"></p>
<p><input type="submit">|<input type="reset"></p>
</form>
1.3info.jsp
${
msg}
1.4FileServlet
package com.simpleteen.servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判断上传的文件是普通表单还是代文件的表单
if (!ServletFileUpload.isMultipartContent(req)) {
return;//终止方法运行,说明这是一个普通的表单,直接返回
}
//创建上传文件的保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件
String uploadPath = this.getServletContext().getRealPath("WEB-INF/upload");
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdir();//创建这个目录
}
//缓存,临时文件
//临时路径,假如文件超过了预期大大小,我们就把他放到一个临时文件中,过几天自动删除,或者提醒用户转存为永久
String tempPath = this.getServletContext().getRealPath("WEB-INF/upload");
File file = new File(tempPath);
if (!file.exists()) {
file.mkdir();//创建这个目录
}
//处理上传的文件,一般都需要通过流来获取,我们可以使用request.getInputStream(),原生态的文件上传流获取,十分麻烦
//但是我们建议使用Apache的文件上传组件来实现,common-fileupload,它现需要依赖于commons-io组件
/*
* ServletFileUpload负责处理上传的文件数据,并将表单中每个输入向封装成一个FileItem对象
* 在使用ServletFileUpload对象解析请求时需要DiskFileItemFactory对象
* 所以,我们需要在进行解析工作前构造好DiskFileItemFactory对象
* 通过ServletFileUpload对象的构造方法或setFileItemFactory()方法设置ServletFileUpload对象的fileItemFactory属性
* */
try {
//1.创建DiskFileItemFactory对象,处理文件上传路径或者大小限制
DiskFileItemFactory factory = getDiskFileItemFactory(file);
//2.获取ServletFileUpload
ServletFileUpload upload = getServletFileUpload(factory);
//3.处理上传的文件
String msg = uploadParseRequest(upload, req, uploadPath);
//servlet请求转发消息
req.setAttribute("msg",msg);
req.getRequestDispatcher("info.jsp").forward(req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
public DiskFileItemFactory getDiskFileItemFactory(File file) {
DiskFileItemFactory factory = new DiskFileItemFactory();
//通过这个工厂设置一个缓冲区,当上传的文件大于这个缓冲区的时候,将它放到临时文件中
factory.setSizeThreshold(1024 * 1024);//缓冲区大小为1M
factory.setRepository(file);//临时目录的保存目录,需要一个File
return factory;
}
public ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);
//监听文件上传进度
upload.setProgressListener(new ProgressListener() {
@Override
//pBytesRead:已经读取到的文件大小
//pContentLength:文件大小
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("总大小:" + pContentLength + ",已上传:" + pBytesRead);
}
});
//处理乱码问题
upload.setHeaderEncoding("UTF-8");
//设置单个文件的最大值
upload.setFileSizeMax(1024 * 1024 * 10);
//设置总共能上传文件的大小
upload.setSizeMax(1024 * 1024 * 10);
return upload;
}
public String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws Exception {
String msg = "";
//把前端请求解析,封装成一个FileItem对象,需要从ServletFileUpload对象中获取
List<FileItem> fileItems = upload.parseRequest(req);
//fileItem每一个表单对象
for (FileItem fileItem : fileItems) {
//判断上传的文件时欧通的表单还是带文件的表单
if (fileItem.isFormField()) {
//getFiledName指的时前端表单控件的name
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");//处理乱码
System.out.println(name + ":" + value);
} else {
//文件
//===============处理文件===============//
//拿到文件名字
String uploadFileName = fileItem.getName();
System.out.println("上传的文件名:" + uploadFileName);
//可能存在文件名不合法
if (uploadFileName.trim().equals("") || uploadFileName == null) {
continue;
}
//获得上传的文件名
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
//获得文件的后缀名
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
/*
* 如果文件后缀名fileExtName 不是我们所需要的
* 就直接return,不处理,告诉用户文件类型不对
* */
System.out.println("文件信息[件名:" + fileName + "---文件类型" + fileExtName + "]");
//可以使用UUID(唯一识别的通用码),保证文件名唯一
//UUID.randomUUID(),随机生成一个唯一识别的通用码
String uuidPath = UUID.randomUUID().toString();
//===============存放地址===============//
//文件真实存在的路径 realPath
String realPath = uploadPath + "/" + uuidPath;
//给每个文件创建一个对应的文件夹
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
//===============文件传输===============//
//获得文件上传的流
InputStream inputStream = fileItem.getInputStream();
//创建一个文件输出流
FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
//创建一个缓冲区
byte[] buffer = new byte[1024 * 1024];
//判断是否读取完毕
int len = 0;
//如果大于0说明还存在数据
while ((len = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
//关闭流
fos.close();
inputStream.close();
fileItem.delete();//上传成功,清除临时文件
}
}
msg = "上传文件成功";
return msg;
}
}
2.邮件发送
发送邮件:SMTP协议
接收邮件:POP3协议
简单邮件:没有附件和图片,纯文本邮件
复杂邮件:有附件和图片
2.1依赖包
使用Java发送E-mail十分简单,但是首先你应该准备JavaMail API 和 Java Activation Framework。
得到两个jar包
- mail.jar
- activation.jar
2.2简单邮件
package com.simpleteen;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
//发送一封简单的邮件
public class MailSimple {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol","smtp");//邮件发送协议
properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
//关于QQ邮箱,还要设置SSL加密,加上以下代码即可,其他邮箱不需要
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
//使用JavaMail发送邮件的5个步骤
//1.创建定义整个应用所需环境信息的Session对象
//QQ邮箱才需要,其他有邮箱不需要
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("[email protected]","授权码");
}
});
//开启Session的debug模式,这样就可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport transport = session.getTransport();
//3.使用邮箱的用户名和授权码脸上邮件服务器
transport.connect("smtp.qq.com","[email protected]","授权码");
//4.创建邮件:写邮件
//注意需要传递Session
MimeMessage message = new MimeMessage(session);
//指明邮件的发送人
message.setFrom(new InternetAddress("[email protected]"));
//指明邮件的收件人,发件人和收件人时一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));
//邮件标题
message.setSubject("只包含文本的简单邮件");
//邮件的文本内容
message.setContent("你好啊!","text/html;charset=UTF-8");
//5.发送邮件
transport.sendMessage(message,message.getAllRecipients());
//6.关闭连接
transport.close();
}
}
2.3复杂邮件(图片)
package com.simpleteen;
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.util.Properties;
//图片
public class MailComplex {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol","smtp");//邮件发送协议
properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
//关于QQ邮箱,还要设置SSL加密,加上以下代码即可,其他邮箱不需要
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
//使用JavaMail发送邮件的5个步骤
//1.创建定义整个应用所需环境信息的Session对象
//QQ邮箱才需要,其他有邮箱不需要
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("[email protected]","授权码");
}
});
//开启Session的debug模式,这样就可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport transport = session.getTransport();
//3.使用邮箱的用户名和授权码脸上邮件服务器
transport.connect("smtp.qq.com","[email protected]","授权码");
//4.创建邮件:写邮件
//注意需要传递Session
MimeMessage message = new MimeMessage(session);
//指明邮件的发送人
message.setFrom(new InternetAddress("[email protected]"));
//指明邮件的收件人,发件人和收件人时一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));
//邮件标题
message.setSubject("复杂邮件,带图片");
//===================复杂的邮件内容==================//
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
//图片需要经过数据处理DataHandler
DataHandler dataHandler = new DataHandler(new FileDataSource("D:\\IdeaProjects\\JavaWeb\\javaweb-mail\\src\\1.jpg"));
image.setDataHandler(dataHandler);//在我们的Body中放入这个处理的图片数据
image.setContentID("1.jpg");//给图片设置一个ID,我们在后面可以使用
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片<img src='cid:1.jpg'>的邮件","text/html;charset=UTF-8");
//描述数据关系
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(text);
mimeMultipart.addBodyPart(image);
//related、mixed
mimeMultipart.setSubType("related");
//设置到消息中,保存修改
message.setContent(mimeMultipart);
message.saveChanges();
//5.发送邮件
transport.sendMessage(message,message.getAllRecipients());
//6.关闭连接
transport.close();
}
}
2.4复杂邮件(附件)
package com.simpleteen;
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.util.Properties;
//附件
public class MailComplex2 {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol","smtp");//邮件发送协议
properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
//关于QQ邮箱,还要设置SSL加密,加上以下代码即可,其他邮箱不需要
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
//使用JavaMail发送邮件的5个步骤
//1.创建定义整个应用所需环境信息的Session对象
//QQ邮箱才需要,其他有邮箱不需要
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("[email protected]","授权码");
}
});
//开启Session的debug模式,这样就可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport transport = session.getTransport();
//3.使用邮箱的用户名和授权码脸上邮件服务器
transport.connect("smtp.qq.com","[email protected]","授权码");
//4.创建邮件:写邮件
MimeMessage mimeMessage = imageMail(session);
//5.发送邮件
transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
//6.关闭连接
transport.close();
}
public static MimeMessage imageMail(Session session) throws MessagingException{
//消息的固定信息
MimeMessage mineMessage = new MimeMessage(session);
//指明邮件的发送人
mineMessage.setFrom(new InternetAddress("[email protected]"));
//指明邮件的收件人,发件人和收件人时一样的,那就是自己给自己发
mineMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));
//邮件标题
mineMessage.setSubject("复杂邮件,附件");
//编写邮件内容 图片、附件、文本
//图片
MimeBodyPart image = new MimeBodyPart();
//图片需要经过数据处理DataHandler
DataHandler dataHandler = new DataHandler(new FileDataSource("D:\\IdeaProjects\\JavaWeb\\javaweb-mail\\src\\1.jpg"));
image.setDataHandler(dataHandler);//在我们的Body中放入这个处理的图片数据
image.setContentID("1.jpg");//给图片设置一个ID,我们在后面可以使用
//文本
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片<img src='cid:1.jpg'>的邮件","text/html;charset=UTF-8");
//附件
MimeBodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(new DataHandler(new FileDataSource("D:\\IdeaProjects\\JavaWeb\\javaweb-mail\\src\\1.txt")));
attachment.setFileName("1.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(attachment);//附件
allFile.addBodyPart(contentText);//正文
allFile.setSubType("mixed");//正文和附件都存在邮件中,所以类型设置为mixed
//设置到消息中,保存修改
mineMessage.setContent(allFile);
mineMessage.saveChanges();
return mineMessage;
}
}
3.网站注册发送邮件
3.1依赖pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
3.2注册页面index.jsp
<form action="${pageContext.request.contextPath}/RegisterServlet.do" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
邮箱:<input type="text" name="email"><br/>
<input type="submit" value="注册">
</form>
3.3回显页面info.jsp
<h1>xxx网站温馨提示</h1>
${message}
3.4实体类user
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private String username;
private String password;
private String email;
}
3.5工具类SendEmail
package com.simpleteen.utils;
import com.simpleteen.pojo.User;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
//网站三秒原则:用户体验
//多线程实现用户体验!(异步处理)
public class SendEmail extends Thread{
//用于用户发送邮件的邮箱
private String from = "[email protected]";
//邮件的用户名
private String username = "[email protected]";
//邮箱的授权码
private String password = "授权码";
//发送邮件的服务器地址
private String host = "smtp.qq.com";
private User user;
public SendEmail(User user){
this.user = user;
}
//重写run方法,在run方法中发送邮件给指定的用户
@Override
public void run(){
try{
Properties properties = new Properties();
properties.setProperty("mail.host",host);//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol","smtp");//邮件发送协议
properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
//关于QQ邮箱,还要设置SSL加密,加上以下代码即可,其他邮箱不需要
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
//1.创建定义整个应用所需环境信息的Session对象
//QQ邮箱才需要,其他有邮箱不需要
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication(username,password);
}
});
//开启Session的debug模式,这样就可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport transport = session.getTransport();
//3.使用邮箱的用户名和授权码脸上邮件服务器
transport.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 = "恭喜您注册成功,您的用户名:" + user.getUsername() + ",您的密码:" + user.getPassword() + ",请妥善保管,如有问题请联系网站客服!";
System.out.println(info);
message.setContent(info,"text/html;charset=UTF-8");
//5.发送邮件
transport.sendMessage(message,message.getAllRecipients());
//6.关闭连接
transport.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
3.6控制类Servlet
package com.simpleteen.servlet;
import com.simpleteen.pojo.User;
import com.simpleteen.utils.SendEmail;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//脚手架
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try{
//接收用户请求,封装成对象
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
User user = new User(username, password, email);
//用户注册成功之后,给用户发送一封信件
//我们使用贤臣来专门发送新建,防止出现耗时,和网站注册人数过多的情况
SendEmail sendEmail = new SendEmail(user);
//启动线程,线程启动之后就会执行run方法来发送邮件
sendEmail.start();
//注册用户
req.setAttribute("message","注册成功,我们已经发了一封带了注册信息的电子邮件");
req.getRequestDispatcher("info.jsp").forward(req,resp);
}catch (Exception e){
e.printStackTrace();
req.setAttribute("message","注册失败");
req.getRequestDispatcher("info.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3.7注意事项
- 里面的邮箱需要自己替换,qq授权码需要自己去qq邮箱里面获取后替换
- 使用了lombok插件,lombok不会的可以自己百度,太多相关的文章,页可以自己修改User类
- 依赖包没有加载有可能需要把依赖包放到tomcat的lib目录下
4.SpringBoot快速实现
4.1pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
4.2application.properties
[email protected]
spring.mail.password=授权码
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
4.3测试
package com.simpleteen.springbootmail;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringbootMailApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("Springboot");//主题
message.setText("Hello");//内容
message.setFrom("[email protected]");//发件人
message.setTo("[email protected]");//收件人
mailSender.send(message);//发送邮件
}
@Test
void contextLoads1() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.setSubject("Springboot");//主题
message.setText("<h1>Hello</h1>",true);//内容
message.setFrom("[email protected]");//发件人
message.setTo("[email protected]");//收件人
//附件
message.addAttachment("1.jpg",new File(""));
mailSender.send(mimeMessage);//发送邮件
}
}