spring boot发送email

<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("替换后的文件不存在,发送邮件失败");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值