前言
笔者需求
笔者的需求所要做的需求是,触发某种条件时,给某些人发送提醒的邮件,邮件内有一个表格,表格内某些数据需要文字标红。
所用框架
- spring-boot-starter-mail(邮件发送)
- easyExcel 3.0.5 (生成excel附件)
代码实现
引入依赖及配置
- pom文件
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- application文件
spring:
mail:
port: ${PORT}
host: ${HOST}
username: ${MAIL_USERNAME}
password: ${MAI_PWD}
from-alias: ${MAIL_ALIAS}
properties:
mail:
smtp:
ssl:
enable: true
auth: true
timeout: 25000
starttls:
enable: true
required: true
具体实现代码
编辑邮件内容
邮件的内容需要一定格式,需要追加一个表格数据。笔者使用的是使用html标签
创建模板,加上参数占位符
,占位符格式自定,注意不要和模板内容冲突,笔者使用的格式为${param}
。表格的占位符笔者使用的是${tableData}。在模板中创建了表格<table>
,标题固定,在标题行下添加此占位符。
具体替换占位符方法如下
private static String getEmailStr(Map<String, String> param, List<XXX> dataList) throws IOException {
String emailTxt = "";
try (InputStream in = new ClassPathResource("templates/finance_warning_email_template.html").getInputStream();
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
CharBuffer charBuffer = CharBuffer.allocate(4096); // 使用缓冲区提高读取效率,可调整大小
StringBuilder sb = new StringBuilder();
while (reader.read(charBuffer) != -1) { // 读取到末尾返回 -1
charBuffer.flip(); // 准备从缓冲区读取数据
sb.append(charBuffer.toString()); // 将缓冲区内容添加到 StringBuilder
charBuffer.clear(); // 清空缓冲区,准备下一次读取
}
emailTxt = sb.toString(); // 获取完整的文本内容
} catch (IOException e) {
log.error("Error reading file: " + e.getMessage(), e);
}
for (Map.Entry<String, String> stringStringEntry : param.entrySet()) {
emailTxt = emailTxt.replaceAll(Pattern.quote(stringStringEntry.getKey()), stringStringEntry.getValue());
}
StringBuilder rowHtmlStr = new StringBuilder();
for (int i = 0; i < dataList.size(); i++) {
XXX xxx = dataList.get(i);
if(xxx .getIsRed() == CustomConsts.TRUE_INT){
rowHtmlStr.append("<tr style=\"background:#fff;color: red;text-align: center;\">");
}else{
rowHtmlStr.append("<tr style=\"background:#fff;color: #000;text-align: center;\">");
}
rowHtmlStr.append("<td>");
rowHtmlStr.append(xxx .getNumber());
rowHtmlStr.append("</td>");
rowHtmlStr.append("<td>");
rowHtmlStr.append(xxx .getName());
rowHtmlStr.append("</td>");
rowHtmlStr.append("<td>");
rowHtmlStr.append(xxx .getProvinceName());
rowHtmlStr.append("</td>");
rowHtmlStr.append("<td>");
rowHtmlStr.append(xxx .getCityName());
rowHtmlStr.append("</td>");
rowHtmlStr.append("</tr>");
}
emailTxt = emailTxt.replace("${tableData}", rowHtmlStr.toString());
return emailTxt;
}
生成excel文件附件
调用框架生成配置
// 使用easyExcel生成excel文件,将生成的文件放入内存之中,不生成临时文件
private InputStream generateExcel(List<XXX> dataList,Integer specialIndex){
RowColorWriteHandler rowColorWriteHandler = new RowColorWriteHandler();
rowColorWriteHandler.setEndRedRow(specialIndex);
ByteArrayOutputStream os = new ByteArrayOutputStream();
EasyExcel.write().registerWriteHandler(rowColorWriteHandler).head(XXX.class).file(os).sheet("告警数据").doWrite(dataList);
byte[] buffer = os.toByteArray();
InputStream inputStream = new ByteArrayInputStream(buffer);
return inputStream;
}
自定义excel样式处理
笔者一开始想直接使用RowWriteHandler里的afterRowDispose方法,测试过程发现该方法内对行操作的样式无效,猜测每个单元格的样式优先级是最高的,而且我的实体类当中也确实指定了默认的单元格样式,所以使用了afterCellDispose来操作每个单元格的样式
public class RowColorWriteHandler implements CellWriteHandler {
// 笔者的需求较为简单,表格数据是有序的,前面N行需要红色文件强调,所以使用了一个变量来确认当前行是否需要调整样式,这个方法如果碰到无序的数据,就有点麻烦了,暂时还没探究别的方法
private Integer endRedRow = 0;
public void setEndRedRow(Integer endRedRow) {
this.endRedRow = endRedRow;
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
Workbook workbook = context.getWriteSheetHolder().getSheet().getWorkbook();
Integer rowIndex = context.getRowIndex();
if(rowIndex == 0 || rowIndex > endRedRow){
return;
}
WriteCellData<?> cellData = context.getFirstCellData();
WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
WriteFont writeFont = new WriteFont();
writeFont.setBold(true);
writeFont.setColor(IndexedColors.RED.getIndex());
writeCellStyle.setWriteFont(writeFont);
writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
Cell cell = context.getCell();
CellStyle cellStyle = StyleUtil.buildCellStyle(workbook, null, writeCellStyle);
cell.setCellStyle(cellStyle);
}
}
发送邮件并携带附件
// 第一个参数为发送人邮箱集合,第二个参数为抄送人集合,第三个为邮件主体名,第四个为邮件内容,第五个为附件的名称,第六个为附件的流,第七个为是否需要发送附件
public void sendHTMLEmailWithAttachment(String[] toArr, String[] ccArr, String subject, String text, String attachmentName, InputStream attachment, boolean isSendAttachment) throws MessagingException, IOException {
if (ArrayUtils.isEmpty(toArr) && ArrayUtils.isEmpty(ccArr)) {
return;
}
MimeMessage message = javaMailSender.createMimeMessage();
// 创建MimeMessageHelper实例来处理复杂的邮件内容(包括附件)
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); // 第二个参数true表示支持多部分消息
try {
helper.setFrom(username, fromAlias);
} catch (UnsupportedEncodingException e) {
log.info("sendHTMLEmailWithAttachment,send failed,ex={}",e.getMessage());
return;
}
if (ArrayUtils.isNotEmpty(toArr)) {
helper.setTo(toArr);
}
helper.setSubject(subject);
helper.setText(text, true);
if (Objects.nonNull(ccArr) && ArrayUtils.isNotEmpty(ccArr)) {
helper.setCc(ccArr);
}
if (isSendAttachment) {
// 添加附件
helper.addAttachment(attachmentName,new ByteArrayResource(IOUtils.toByteArray(attachment)));
}
javaMailSender.send(message);
}