SpringBoot中简单邮件上传和附件上传(中文乱码问题)

SpringBoot中简单邮件上传和增加附件上传

首先我们需要先导入pom依赖

         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>   

配置SpringBoot yml或properties的配置,这里展示的是yml配置

spring:
  mail:
    host: smtp.exmail.qq.com   #每个邮箱都有host这边展示的是qq企业邮箱
    port: 465
    username: [email protected] 邮箱地址 #(并且是发件方)
    password: #你的邮箱授权码
    protocol: smtp #协议
    properties:
      mail:
        smtp:
          auth: true
          ssl:
            enable: true

我们还需要对邮箱进行一个配置
发送方必须要开启smtp,获取到的授权码,界面如下:
SpringBoot中简单邮件上传和附件上传(中文乱码问题)_第1张图片
将获取到授权码输入到spring.mail.password中

简单的发送邮件

 @Autowired
    private JavaMailSender mailSender;


    private static final String RECEPTION = "[email protected]";


    public ResultUtil sendNormalMsg() {
        ResultUtil resultUtil = new ResultUtil();
        //建立邮件消息
        SimpleMailMessage mainMessage = new SimpleMailMessage();
        System.out.println(USER_NAME);
        mainMessage.setFrom(USER_NAME);
        mainMessage.setTo(RECEPTION);
        mainMessage.setSubject("测试发送邮件标题");
        mainMessage.setText("测试发送邮件正文");
        mailSender.send(mainMessage);
        return resultUtil.setStatus(ErrorType.ErrorTypeEnum.SUCCESS).setMsg("发送成功");
    }

以附件的形式发送邮件,并且解决附件名称中中文乱码问题

@Service
public class EmailServiceImpl implements IEmailService {

    private static Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);


    @Autowired
    private JavaMailSender mailSender;

    private static final String EMAILSUBJECT = "电梯设备故障统计报表";

  /**
   * 解决附件名称中文乱码问题
  **/
    static {
        System.setProperty("mail.mime.splitlongparameters", "false");
    }


    
    @Override
    public ResultUtil sendFileMsg(EmailModelDTO address) {
        ResultUtil resultUtil = new ResultUtil();

        InternetAddress[] toArray = new InternetAddress[address.getToDddress().size()];
        try {
            for (int i = 0; i < toArray.length; i++) {
                toArray[i] = new InternetAddress(address.getToDddress().get(i));
            }
            //创建临时文件
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            mimeMessageHelper.setTo(toArray);//收件人
            mimeMessageHelper.setFrom(USER_NAME);
            mimeMessageHelper.setText(EMAILSUBJECT);
            mimeMessageHelper.setSubject(EMAILSUBJECT + DateUtils.format(System.currentTimeMillis(), DateUtils.PATTERN_24_YYYYMMDDHHMMSS));
            String filename = EMAILSUBJECT + DateUtils.format(System.currentTimeMillis(), DateUtils.PATTERN_24_YYYYMMDDHHMMSS) + ".xlsx";
            mimeMessageHelper.addAttachment(filename, new ByteArrayResource(IOUtils.toByteArray(fileImport())), "application/vnd.ms-excel;charset=UTF-8");
            mailSender.send(mimeMessage);
            logger.info("sendFileMail success");
        } catch (MessagingException e) {
            logger.info("sendFileMail fail." + e);
            e.printStackTrace();
            return resultUtil.setStatus(ErrorType.ErrorTypeEnum.FAILURE).setMsg("发送失败");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil.setStatus(ErrorType.ErrorTypeEnum.SUCCESS).setMsg("发送成功");
    }
	public InputStream fileImport() {
		 SXSSFWorkbook workbook = new SXSSFWorkbook();
 		 Sheet sheet = workbook.createSheet("sheet");
  		 InputStream in = null;

        //临时缓冲区
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            String filename = "统计报表" + DateUtils.format(System.currentTimeMillis(), DateUtils.PATTERN_24_YYYYMMDDHHMMSS) + ".xlsx";
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            workbook.write(out);
            byte[] bookByteAry = out.toByteArray();
            in = new ByteArrayInputStream(bookByteAry);
            out.write(bookByteAry);
            out.flush();
            out.close();
            return in;

        } catch (IOException e) {
            e.printStackTrace();
        }

解决附件中的中文乱码问题,加一个静态代码块,在初始化的时候执行它

static {
        System.setProperty("mail.mime.splitlongparameters", "false");
	}

你可能感兴趣的:(java,spring,boot,后端)