在我写大学生高考志愿填报的时候,将推荐出来的专业表的信息发送到指定的账户的邮件中
下面代码的实现讲解:
- 首先创建配置文件,配置邮箱账户的信息
- 配置用于生成表格的实体类,实体类中的信息就对应着Excel表中的信息
- 逻辑的具体实现:
- 首先从Cookie中获取账户的邮箱信息,(我在cookie中只存了账户的邮箱号,没有帐户其他的信息)。
- 获取我查询结果的datas
- 将datas封装成Excel表格
- 发送带有Excel表格的邮件
- 将本地的Excel表格删除掉
application.yml:
java">spring:mail:host: smtp.qq.comusername: 2asdfasdf7@qq.compassword: asdoighwakjfnsproperties:mail:smtp:ssl:enable: true
entity层:(实体类中的血法)
java">@Getter
@Setter
@TableName("t_pitch")
public class Pitch implements Serializable {private static final long serialVersionUID = 1L;@ExcelIgnore@TableId(value = "id", type = IdType.AUTO)private Integer id;/*** 院校代号*/@ExcelProperty("院校代号")@TableField("schoolCode")private String schoolCode;/*** 学校名称*/@ExcelProperty("学校名称")@TableField("schoolName")private String schoolName;/*** 专业代号*/@ExcelProperty("专业代号")@TableField("pCode")private String pCode;/*** 专业名称*/@ExcelProperty("专业名称")@TableField("pName")private String pName;/*** 最低投档分数*/@ExcelProperty("最低投档分数")@TableField("lowestScore")private String lowestScore;/*** 最低投档位次*/@ExcelProperty("最低投档位次")@TableField("lowestRank")private String lowestRank;
}
controller层代码:
java">@RequestMapping("/sendExcel")
@ResponseBody
public void sendExcel(HttpServletRequest request, HttpServletResponse response) throws MessagingException {//1、获取cookie中的邮箱信息Cookie[] cookies = request.getCookies();for(Cookie cookie:cookies){if(cookie.getName().equals("email")){email1 = cookie.getValue();break;}}//2、获取表中的信息 datas,然后生成xlsx//写文件:String tempFilePath=PATH+"专业推荐表.xlsx";EasyExcel.write(tempFilePath,Pitch.class).sheet("统计表1").doWrite(datas);//3、发送信息MimeMessage message = javaMailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message,true);helper.setFrom("211111111@qq.com");helper.setTo(email1);helper.setSubject("邮件发送数据");helper.setText("以下是为您导出的专业推荐表");File file = new File(tempFilePath);DataSource source= new FileDataSource(file);helper.addAttachment(file.getName(),source);javaMailSender.send(message);boolean delete = file.delete();if (delete) {System.out.println("Temporary file deleted successfully.");} else {System.out.println("Failed to delete temporary file.");}}