1.配置项目文件目录,我配置的是这样的:
2:配置pom.xml
参照对比添加包依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
3:配置application.properties文件
获取邮箱授权码的方式可以自行百度。
#邮箱服务器地址
spring.mail.host=smtp.qq.com
#发件人地址
spring.mail.username=xxxx@qq.com
#邮箱的授权码
spring.mail.password=xxxxx
spring.mail.default-encoding=utf-8
#发件人
mail.fromMail.addr=xxxxx@qq.com
4. 配置MailService和MailServiceImpl文件
MailService文件
package com.email.service;
public interface MailService {
//发送普通邮件
void sendSimpleMail(String to,String subject,String content);
//发送Html邮件
void sendHtmlMail(String to,String subject,String content);
//发送带附件的邮件
void sendAttachmentMail(String to,String subject,String content,String filePath);
}
MailServiceImpl文件
package com.email.service.impl;
import com.email.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
@Component
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${mail.fromMail.addr}")
private String from;
@Override
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try{
mailSender.send(message);
System.out.println("success");
}catch (Exception e){
System.out.println("fail"+e);
}
}
@Override
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true); //true表示需要创建一个multipart message
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
System.out.println("html邮件发送成功");
} catch (MessagingException e) {
System.out.println("发送html邮件时发生异常!"+e);
}
}
@Override
public void sendAttachmentMail(String to, String subject, String content, String filePath) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
//helper.addAttachment("test"+fileName, file);
mailSender.send(message);
System.out.println("带附件的邮件已经发送。");
} catch (MessagingException e) {
System.out.println("发送带附件的邮件时发生异常!"+e);
}
}
}
5:MailController文件
package com.email.controller;
import org.testng.annotations.Test;
import com.email.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@RestController
@RequestMapping("/mail")
public class MailController {
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
@RequestMapping("/sendSimpleMail")
public String sendSimpleMail() {
String to = "xxxx@qq.com";
String subject = "test html mail";
String content = "hello, this is html mail!";
mailService.sendSimpleMail(to, subject, content);
return "success";
}
@RequestMapping("/sendHtmlMail")
public String sendHtmlMail() {
String to = "xxxx@qq.com";
String subject = "test html mail";
String content = "hello, this is html mail";
mailService.sendHtmlMail(to, subject, content);
return "success";
}
@Test
@RequestMapping("/sendAttachmentsMail")
public String sendAttachmentsMail() {
String filePath="E:\\11111.txt";
mailService.sendAttachmentMail("xxxx@qq.com", "主题:带附件的邮件", "有附件,请查收!", filePath);
return "success";
}
@Test
@RequestMapping("/sendTemplateMail")
public String sendTemplateMail() {
//创建邮件正文
Context context = new Context();
context.setVariable("user", "1111");
context.setVariable("web", "tttt");
context.setVariable("company", "我是一个公司");
context.setVariable("product","我是一个产品");
String emailContent = templateEngine.process("emailTemplate", context);
mailService.sendHtmlMail("xxxx@qq.com","主题:这是模板邮件",emailContent);
return "success";
}
}
6:emailTemplate.html文件
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:text="'尊敬的 ' + ${user} + '用户:'"></p>
<p th:text=" '恭喜您注册成为'+${web}+'网的用户,同时感谢您对'+${company}+'的关注与支持并欢迎您使用'+${product}+'的产品与服务。'"></p>
</body>
</html>
7:比较重要的EmailApplication启动文件
package com.email;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "com.email.*")
public class EmailApplication {
public static void main(String[] args) {
SpringApplication.run(EmailApplication.class, args);
System.out.println("Success");
}
}
8:运行EmailApplication右击run。在浏览器输入http://localhost:8080/mail/+对应的方法名即可发送成功。例如:
即可成功。
======================分割线============================
扩展:修改项目为邮件内容可编辑,收件人可自我选择
1.新建email类
package com.email.email;
public class Email {
private String to;
private String object;
private String content;
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Email{" +
"to='" + to + '\'' +
", object='" + object + '\'' +
", content='" + content + '\'' +
'}';
}
}
2.新建一个方法
@ResponseBody
@RequestMapping("/sendSimpleMail")
public String sendSimpleMail(@RequestBody Email email) {
mailService.sendSimpleMail(email.getTo(),email.getObject(),email.getContent());
return "success";
}
3.在templates文件中新建html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>第一个HTML页面</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h1>Hello Spring Boot!!!</h1>
<p th:text="${hello}"></p>
收件人:<input type="text" id="shou">
<br>
标题:<input type="text" id="title">
<br>
内容:<input type="text" id="content">
<br>
附件:<input type="file" id="file">
<br>
<button id="b1">发送</button>
</body>
<script>
$(document).ready(function(){
$("#b1").click(function(){
$.ajax({
type:"post",
url:"/mail/sendSimpleMail",
dataType : "json",
data:JSON.stringify({
to :$("#shou").val(),
object : $("#title").val(),
content : $("#content").val()
}),
contentType: "application/json",
success : function () {
$("input[name='test']").val("").focus();
}
})
});
});
</script>
</html>
4.注:要在application.properties里配置新的内容。如下:
spring:
thymeleaf:
prefix: classpath:/templates/
5:注:在html页面中使用ajax时,data数据要JSON.Stringify(),不然会报错,如下:
6:附件部分获取不到文件地址,如有大佬,看到请指教怎么获取到file的地址。感谢!!!
注:参考https://blog.csdn.net/ZZ2713634772/article/details/79576930