在項目開發中,除了需要短信驗證外,有時候為了節省 短信費也會使用郵件發送。下面一起來看看Spring Boot如何發送郵件。
本文以163郵箱為例進行郵件發送功能,需要把用戶信息以附件的形式發送,其他郵箱的配置也都大同小異。
一、郵件服務器與傳輸協議
要在網絡上實現郵件功能,必須要有專門的郵件服務器。這些郵件服務器類似於現實生活中的郵局,它主要負責接收用戶投遞過來的郵件,並把郵件投遞到郵件接收者的電子郵箱中。
SMTP服務器地址:一般是 smtp.xxx.com,比如163郵箱是smtp.163.com,qq郵箱是smtp.qq.com。
SMTP協議:通常把處理用戶smtp請求(郵件發送請求)的服務器稱之為SMTP服務器(郵件發送服務器)。
POP3協議:通常把處理用戶pop3請求(郵件接收請求)的服務器稱之為POP3服務器(郵件接收服務器)。
二、Java發送郵件

2.1獲取授權碼
網易郵箱–>設置–>QQ郵箱–>郵箱設置–>賬戶–>POP3/SMTP/IMAP
開啟POP3/SMTP服務,然后獲取16位授權碼(注意不要將授權碼泄露,一個賬戶可以擁有多個授權碼)

2.2添加依賴
<!--excel依賴-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
<!--easyexcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
<!--郵件依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--把配置文件的信息,讀取並自動封裝成實體類-->
<dependency>
<groupId >org.springframework.boot</groupId >
<artifactId >spring-boot-configuration-processor</artifactId >
<optional >true</optional >
</dependency>
2.3. 配置郵箱信息
需要注意的是password不是郵箱登錄密碼,而是2.1中獲取的授權碼。
#文件下載路徑
file:
path:
# window配置 D:/home/mail Linux: /home/app/mail
mail: D:/home/mail
spring:
mail:
protocol: smtps
from: xxx@163.com
host: smtp.163.com
username: xxxx@163.com
password: xxxxxxxxxx
port: 465
properties:
mail:
smtp:
auth: true
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory
starttls:
enable: true
required: true
2.4. 發送郵件
與配置文件映射的實體類
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="spring.mail")
@Data
public class MailConfiguartion {
private String protocol;
private String from;
private String host;
private String username;
private String password;
private String port;
}
controller
import com.baba.mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/sendMail", method = RequestMethod.GET)
public void sendMail() throws IOException {
userService.sendMail();
}
}
service
import com.baba.mybatis.entity.MailConfiguartion;
import com.baba.mybatis.entity.User;
import com.baba.mybatis.mapper.UserMapper;
import com.baba.mybatis.service.UserService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.activation.DataHandler;
import javax.activation.DataSource;
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.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Properties;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private MailConfiguartion mailConfiguartion;
@Value("${file.path.mail}")
private String downloadFilePath;
@Override
public void sendMail() throws IOException {
//查詢生成excel文件所需要的數據
List<User> userList = userMapper.queryUserInfo();
//生成excel保存到downloadFilePath
File file = createFile(userList);
//to :郵件接收人
String to = "xxxxx@qq.com";
//發送郵件
sendMailFile(to, file);
}
void sendMailFile(String to, File file) {
// 創建郵件會話
Properties properties = new Properties();
properties.put("mail.transport.protocol", mailConfiguartion.getProtocol());
properties.put("mail.smtp.host", mailConfiguartion.getHost());
properties.put("mail.smtp.port", mailConfiguartion.getPort());
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailConfiguartion.getUsername(), mailConfiguartion.getPassword());
}
});
try {
// 創建郵件消息體
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailConfiguartion.getFrom()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("用戶信息通知");
// 創建多部分消息體
Multipart multipart = new MimeMultipart();
// 添加文本消息
BodyPart messageBodyPart = new MimeBodyPart();
StringBuffer sb=new StringBuffer();
sb.append("這是一封測試郵件").append("\n");
sb.append("所有用戶信息見附件").append("\n");
messageBodyPart.setText(sb+"");
multipart.addBodyPart(messageBodyPart);
// 添加附件
messageBodyPart = new MimeBodyPart();
String filename = file.getName();
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// 設置整個郵件消息體
message.setContent(multipart);
// 發送郵件
Transport.send(message);
System.out.println("郵件發送成功");
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
private File createFile(List<User> userList) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("用戶信息");
// 創建表頭行
Row headerRow = sheet.createRow(0);
Cell headerCell1 = headerRow.createCell(0);
Cell headerCell2 = headerRow.createCell(1);
Cell headerCell3 = headerRow.createCell(2);
headerCell1.setCellValue("編號");
headerCell2.setCellValue("姓名");
headerCell3.setCellValue("年齡");
for (int i = 0; i < userList.size(); i++) {
// 創建數據行
Row dataRow1 = sheet.createRow(i + 1);
Cell dataCell1 = dataRow1.createCell(0);
Cell dataCell2 = dataRow1.createCell(1);
Cell dataCell3 = dataRow1.createCell(2);
dataCell1.setCellValue(userList.get(i).getId());
dataCell2.setCellValue(userList.get(i).getName());
dataCell3.setCellValue(userList.get(i).getAge());
}
// 文件目錄不存在則創建文件夾及文件,若存在則覆蓋文件
File file = new File(downloadFilePath + "/" + "用戶信息.xlsx");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
} else {
file.delete();
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(downloadFilePath + "/" + "用戶信息.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
return file;
}
}
2.5. 發送效果
正文換行sb.append("這是一封測試郵件").append("\n");
或者sb.append("這是一封測試郵件").append("<br>");

