1.引入依赖
<!--发送邮件需要的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.邮箱信息配置类
@Component
@Configuration
@ConfigurationProperties(prefix = "mail")
public class EmailConfig {
private String host;
private Integer port;
private boolean ssl;
private String username;
private String password;
private String formName;
@Value("#{'${mail.to}'.split(',')}")
private String[] to;
}
配置文件
server:
port: 8027
spring:
servlet:
multipart:
max-file-size: 50MB
max-request-size: 70MB
mail:
host: smtp.qq.com
port: 25
username: xxx@qq.com
password: xxxx
formName: 皓亮君
to: xxxx1@qq.com,xxxx2@qq.com
3.发送邮件的工具类
下面工具类对外提供服务的sendEmailByParam()方法,处理发送邮件的逻辑在send()方法里
- 支持发送带网页样式的邮件内容
- 支持附件使用File本地文件和MultipartFile网页文件
public class EmailUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class);
private EmailUtil() {
}
private static class FileInfo {
public FileInfo(String name, InputStream inputStream) {
this.name = name;
this.inputStream = inputStream;
}
private String name;
private InputStream inputStream;
public String getName() {
return name;
}
public InputStream getInputStream() {
return inputStream;
}
}
public static boolean sendEmailByParam(EmailConfig emailConfig, List<File> fileList, String subject, String content) {
try {
List<FileInfo> fileInfoList = new ArrayList<>();
if (fileList != null) {
for (File file : fileList) {
fileInfoList.add(new FileInfo(file.getName(), new FileInputStream(file)));
}
}
send(emailConfig, fileInfoList, subject, content);
return true;
} catch (Exception e) {
LOGGER.error("邮件发送失败: errorMsg={}", e.getMessage());
return false;
}
}
public static boolean sendEmailByParam(EmailConfig emailConfig, MultipartFile[] fileList, String subject, String content) {
try {
List<FileInfo> fileInfoList = new ArrayList<>();
if (fileList != null) {
for (MultipartFile file : fileList) {
fileInfoList.add(new FileInfo(file.getName(), file.getInputStream()));
}
}
send(emailConfig, fileInfoList, subject, content);
return true;
} catch (Exception e) {
LOGGER.error("邮件发送失败: errorMsg={}", e.getMessage());
return false;
}
}
private static void send(EmailConfig emailConfig, List<FileInfo> fileList, String subject, String text) throws Exception {
JavaMailSenderImpl jms = new JavaMailSenderImpl();
MimeMessage mimeMessage = jms.createMimeMessage();
boolean multipart = fileList.size() > 0;
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart, "utf-8");
jms.setHost(emailConfig.getHost());
jms.setPort(emailConfig.getPort());
jms.setUsername(emailConfig.getUsername());
jms.setPassword(emailConfig.getPassword());
Properties p = new Properties();
p.setProperty("mail.smtp.auth", "true");
if (emailConfig.isSsl()) {
p.setProperty("mail.transport.protocol", "smtp");
p.put("mail.smtp.ssl.enable", "true");
MailSSLSocketFactory sf = null;
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
p.put("mail.smtp.ssl.socketFactory", sf);
}
jms.setJavaMailProperties(p);
helper.setFrom(emailConfig.getUsername(), emailConfig.getFormName());
helper.setTo(emailConfig.getTo());
helper.setSubject(subject);
helper.setText(text, true);
for (FileInfo fileInfo : fileList) {
ByteArrayDataSource attachment = new ByteArrayDataSource(fileInfo.getInputStream(), "application/octet-stream");
helper.addAttachment(fileInfo.getName(), attachment);
}
jms.send(mimeMessage);
LOGGER.info("发送成功!");
}
}
4.main函数测试发送邮件
public static void main(String[] args) {
EmailConfig emailConfig = new EmailConfig();
emailConfig.setHost("smtp.qq.com");
emailConfig.setPort(25);
emailConfig.setSsl(false);
emailConfig.setUsername("xxx@qq.com");
emailConfig.setPassword("xxx");
emailConfig.setFormName("皓亮君");
emailConfig.setTo(new String[]{"xxx@qq.com"});
List<File> fileList = Arrays.asList(new File("C:\\Users\\Administrator\\Desktop\\test\\1.txt"), new File("C:\\Users\\Administrator\\Desktop\\test\\2.txt"));
sendEmailByParam(emailConfig, fileList, "邮件主题", "邮件的内容");
}
运行完成了打印发送成功,则邮件成功发送了到收件人手中
5.集成js插件ueditor编写带样式的邮件正文
5.1.页面集成插件
依赖的文件比较多,就不贴代码,需要的可以重文章下方的github地址中自行下载项目源代码,页面上集成ueditor插件代码如下
<!DOCTYPE HTML>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<meta http-equiv="Cache-Control" content="no-siteapp"/>
<title>邮件内容编辑</title>
</head>
<body>
<form id="sendEmailForm" action="/sendEmail" method="post" ENCTYPE="multipart/form-data">
<div>
邮件标题 <input type="text" class="input-text" name="subject">
</div>
<div>
邮件正文:
<script id="editor" name="text" type="text/plain"></script>
</div>
<div>
附件一:
<input type="file" name="file">
</div>
<div>
附件二:
<input type="file" name="file">
</div>
<button class="btn btn-primary radius" type="submit" id="save"> 保存</button>
</form>
<script type="text/javascript" charset="utf-8" src="/js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/js/ueditor/ueditor.all.js"></script>
<script type="text/javascript" charset="utf-8" src="/js/ueditor/lang/zh-cn/zh-cn.js"></script>
<script>
var ue = UE.getEditor('editor', {
autoHeightEnabled: true,
autoFloatEnabled: true,
initialFrameHeight: 170
});
</script>
</body>
</html>
5.2.编写后台接口接收数据并发送邮件
@RestController
public class EmailController {
@Autowired
private EmailConfig emailConfig;
@PostMapping("/sendEmail")
public String sendEmail(@RequestParam String subject, @RequestParam String text, @RequestParam("file") MultipartFile[] multipartFileList) {
boolean flag=EmailUtil.sendEmailByParam(emailConfig, multipartFileList, subject, text);
return flag?"发送成功!":"发送失败!";
}
}
运行项目后在页面上方访问http://localhost:8027/, 然后根据插件功能自行调整样式和排版格式,选择是否需要上传文件,然后在点保存提交请求。
看到下面的信息则表示邮件已成功发送。
6.项目配套代码
github地址
创作不易,要是觉得我写的对你有点帮助的话,麻烦在github上帮我点下 Star
【SpringBoot框架篇】其它文章如下,后续会继续更新。
|