<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>${mail.version}</version> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
spring.mail.host=smtp.cin.gov.cn spring.mail.username=zhengwuzixun@mohurd.gov.cn spring.mail.password=mohurd@2018 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility;
@Override public void sendMail(ConsultEsVo vo) throws Exception { File srcFile = new File("住房城乡建设部网站政务咨询问题答复单.docx"); File destFile = new File("住房城乡建设部网站政务咨询问题答复单(替换后).docx"); FileUtils.copyInputStreamToFile(this.getClass().getResourceAsStream("/住房城乡建设部网站政务咨询问题答复单.docx"), srcFile); if (!srcFile.exists()) { LOGGER.warn("ConsultEsServiceImpl sendMail 没有找到源模板文件"); throw new RuntimeException("没有找到源模板文件,发送邮件失败"); } String srcPath = srcFile.getPath(); String destPath = destFile.getPath(); boolean replaceResult = WordUtil.replaceAndGenerateWord(srcPath, destPath, vo); if (!replaceResult) { LOGGER.warn("ConsultEsServiceImpl sendMail 生成邮件附件失败"); throw new RuntimeException("生成邮件附件失败,发送邮件失败"); } File file = new File(destPath); if (file != null && file.exists()) { try { FileSystemResource ip = new FileSystemResource(file); if (ip == null) { LOGGER.warn("ConsultEsServiceImpl sendMail 附件文件未找到!"); throw new RuntimeException("没有找到附件文件,发送邮件失败"); } System.setProperty("mail.mime.splitlongparameters", "false"); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(from); helper.setTo(to); helper.setSubject("政务问题咨询:" + vo.getTitle()); helper.setText(getBody(vo)); helper.addAttachment(MimeUtility.encodeText("住房城乡建设部网站政务咨询问题答复单.docx"), ip); mailSender.send(mimeMessage); } catch (Exception e) { throw e; } finally { if (file != null && file.exists()) { file.delete(); } System.setProperty("mail.mime.splitlongparameters", "true"); } } else { LOGGER.warn("ConsultEsServiceImpl sendMail 不存在文件[{}]", destPath); throw new RuntimeException("替换后的文件不存在,发送邮件失败"); } }