刚开始我写的代码是这样的
private Mail initMail(List<Map<String , String>> writeInFieldsList , List<Map<String , ?>> allFieldsList , String smallCity) throws Exception {byte[] excelBytes = CustomExcelUtils.trafficSignalWarning(writeInFieldsList, allFieldsList , Constant.sheetHeaderAlias , Constant.indexedComparator);String renderDataToTemplate = ThymeleafTemplateUtils.trafficSignalWarning(allFieldsList);String subject = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE) + "关键业务指标预警-" + smallCity;Mail mail = new Mail();mail.setSubject(subject);mail.setFrom(javaMailSenderProperties.getUsername());mail.setTo("fengliangliang@xiaoning.cn");
// mail.setCc("fengliangliang@xiaoning.cn");mail.setContent(renderDataToTemplate);mail.setAttachName("业绩预警" + ".xlsx");mail.setAttach(excelBytes);return mail;}/*** 发送MIME类型的邮件* @param email 邮件对象*/public void sendMimeMail(Mail email) throws MessagingException {//基于这个对象可以发送HTML,或者携带附件的二进制邮件MimeMessage message= javaMailSender.createMimeMessage();if(StringUtils.isNotBlank(email.getCc())) {message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(email.getCc()));}//构建发送模板邮件的对象MimeMessageHelper helper = new MimeMessageHelper(message,true);//设置发送邮箱helper.setFrom(email.getFrom());//设置接收邮箱helper.setTo(InternetAddress.parse(email.getTo()));//设置邮件名(主题)helper.setSubject(email.getSubject());//设置邮件内容helper.setText(email.getContent() ,true);//这里可以发送带有附件的邮件,如果没有附件可以省略,就不在多做描述if ( StringUtils.isNotBlank(email.getAttachName()) && email.getAttach() != null ) {ByteArrayResource byteArrayResource = new ByteArrayResource( email.getAttach() );helper.addAttachment(email.getAttachName() , byteArrayResource);}//发送邮件javaMailSender.send(message);}
结果在邮件中看到的附件是这样的
直接打开
我将附件另存为一个正常的 excel 名称
结果可以正常打开
后来我将代码中设置的附件名改成不带中文,结果好了
private Mail initMail(List<Map<String , String>> writeInFieldsList , List<Map<String , ?>> allFieldsList , String smallCity) throws Exception {byte[] excelBytes = CustomExcelUtils.trafficSignalWarning(writeInFieldsList, allFieldsList , Constant.sheetHeaderAlias , Constant.indexedComparator);String renderDataToTemplate = ThymeleafTemplateUtils.trafficSignalWarning(allFieldsList);String subject = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE) + "关键业务指标预警-" + smallCity;Mail mail = new Mail();mail.setSubject(subject);mail.setFrom(javaMailSenderProperties.getUsername());mail.setTo("fengliangliang@xiaoning.cn");
// mail.setCc("fengliangliang@xiaoning.cn");mail.setContent(renderDataToTemplate);mail.setAttachName("traffic_signal_warning_center" + ".xlsx");mail.setAttach(excelBytes);return mail;}