1,你需要申請一個郵箱
1,申請一個 163 的郵箱並登入,這個很簡單
2,如下圖進入設置

3,確定下圖中的選項為開啟狀態,切記,開啟功能的時候,系統會給你分配一個授權碼,只會顯示一次,一定要記錄下來

2,SpringBoot 框架整合
1,pom.xml
<!-- FreeMarker 模板引擎,用於生成郵件內容 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- 郵件發送的依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2,application.yml
spring:
freemarker:
enabled: true
cache: true
content-type: text/html
charset: UTF-8
check-template-location: true
template-loader-path: classpath:templates
# prefix:
suffix: .ftl
prefer-file-system-access: true
allow-request-override: false
allow-session-override: false
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
mail:
host: smtp.163.com
username: 你的郵箱賬號
password: 授權碼(注意,不是郵箱的密碼)
3,封裝一個文件類,在發送附件和靜態資源的時候使用
package com.hwq.common.vo;
import lombok.Getter;
import lombok.Setter;
import java.io.File;
@Getter
@Setter
public class MailFileVo {
/**
* 1,當作為靜態資源時,代表資源的唯一標識,可以插入到 html 內容中,如 img 標簽的 src 屬性
* 2,當作為附件時,作為附件的名稱
*/
private String name;
/**
* 文件對象,可以是附件也可以是靜態資源
*/
private File file;
}
4,封裝一個發送郵件的類,
package com.hwq.web.server.service;
import com.hwq.common.vo.MailFileVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String fromMail;
/**
* 發送郵件的方法
*
* 三種收件人模式的解釋
* 1,Message.RecipientType.TO 直接接收人
* 2,Message.RecipientType.CC 明抄送收件人
* 3,Message.RecipientType.BCc 暗抄送收件人(不會 被直接收件人 和 明抄送收件人 看見的收件人)
*
* @param toAddr 收件人的 郵件地址
* @param ccAddr 抄送人的 郵件地址
* @param subject 郵件標題
* @param html 郵件內容
* @param srcVos 靜態資源類
* @param athVos 附件資源類
*/
public void sendMail(String[] toAddr, String[] ccAddr, String subject, String html, List<MailFileVo> srcVos, List<MailFileVo> athVos) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromMail);
helper.setSubject(subject);
helper.setText(html, true);
if (toAddr != null && toAddr.length > 0) {
Address[] addresses = new Address[toAddr.length];
for (int i = 0; i < toAddr.length; i ++) {
addresses[i] = new InternetAddress(toAddr[i]);
}
message.setRecipients(Message.RecipientType.TO, addresses);
}
if (ccAddr != null && ccAddr.length > 0) {
Address[] addresses = new Address[ccAddr.length];
for (int i = 0; i < ccAddr.length; i ++) {
addresses[i] = new InternetAddress(ccAddr[i]);
}
message.setRecipients(Message.RecipientType.CC, addresses);
}
if (CollectionUtils.isNotEmpty(srcVos)) {
for (MailFileVo srcVo : srcVos) {
helper.addInline(srcVo.getName(), srcVo.getFile());
}
}
if (CollectionUtils.isNotEmpty(athVos)) {
for (MailFileVo athVo : athVos) {
helper.addAttachment(athVo.getName(), athVo.getFile());
}
}
mailSender.send(message);
} catch (MessagingException ex) {
ex.printStackTrace();
throw new RuntimeException(ex.getMessage());
}
}
}
5,准備一個郵件模板,mail.ftl
<style type="text/css">
.mail-table {
width: 100%;
border-top: 1px solid #333;
border-left: 1px solid #333;
border-collapse: collapse;
border-spacing: 0;
}
.mail-table tr {
}
.mail-table th {
background: rgb(255, 204, 204);
height: 40px;
border-bottom: 1px solid #333;
border-right: 1px solid #333;
}
.mail-table td {
height: 36px;
text-indent: 14px;
border-bottom: 1px solid #333;
border-right: 1px solid #333;
}
</style>
<h3>${title}</h3>
<table class="mail-table">
<tr>
<th>序號</th>
<th>賬號</th>
<th>昵稱</th>
</tr>
<#list users as user>
<tr>
<td>${user_index + 1}</td>
<td>${user.account}</td>
<td>${user.nickname}</td>
</tr>
</#list>
</table>
<!-- 圖片地址固定為 cid:封裝的 MailFileVo 的 name 屬性 -->
<img src="cid:battle-field" />
6,測試,寫一個控制器發送郵件
package com.hwq.web.server.controller;
import com.hwq.common.data.entity.User;
import com.hwq.common.util.HttpUtil;
import com.hwq.common.vo.MailFileVo;
import com.hwq.web.server.service.MailService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RequestMapping("mail")
@RestController
public class MailController {
@Autowired
private MailService mailService;
@Autowired
private Configuration configuration;
@Value("${file.save.location}")
private String rootPath; // 這是你靜態資源存放的根路徑,從配置文件讀取
@RequestMapping("/send")
public ResponseEntity<Object> sendSimpleMail() throws IOException, TemplateException {
Template template = configuration.getTemplate("mail.ftl");
Map<String, Object> model = new HashMap<>();
List<User> users = new ArrayList<>();
for (int i = 0; i < 10; i ++) {
User user = new User();
user.setAccount("102020200" + i);
user.setNickname("張三李四" + i);
users.add(user);
}
model.put("title", "測試的郵件");
model.put("users", users);
String[] toAddr = new String[] {"huangweiqiang@ysstech.com"};
String[] ccAddr = new String[] {"524086452@qq.com"};
String subject = "測試郵件,別當真";
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
List<MailFileVo> srcVos = new ArrayList<>();
MailFileVo mailFileSrc = new MailFileVo();
mailFileSrc.setName("battle-field");
mailFileSrc.setFile(new File(rootPath + "/static/battle-field.jpg"));
srcVos.add(mailFileSrc);
List<MailFileVo> athVos = new ArrayList<>();
MailFileVo mailFileAth = new MailFileVo();
mailFileAth.setName("你的附件.txt");
mailFileAth.setFile(new File(rootPath + "/static/fu-jian.txt"));
athVos.add(mailFileAth);
// return HttpUtil.r200(html);
mailService.sendMail(toAddr, ccAddr, subject, html, srcVos, athVos);
return HttpUtil.r200("發送成功");
}
}
3,瀏覽器訪問 http:ip:port/mail/port