SpringBoot stream files using JavaMail export scheme

In the project, we may encounter a scene using the mailbox export file, there are two files in the build process, one is a server or elsewhere path, you can get the file stream; one is that we do not want to build the file path, just use case flow directly exported file, because the first is relatively simple, I'm just here to build processing flow export program.

Preparatory

  1. Create a new project springboot
  2. JavaMail rely introduced in the pom file
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
  1. Code written messages sent
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 使用JavaMail导出带附件的字节流邮件
     * @param subject 邮件主题
     * @param fromEmail 发送的邮箱地址
     * @param toEmail 收件的邮箱地址
     * @param bodyContent 邮件正文内容
     * @param fileName 导出到邮箱的附件名称
     * @param attachmentByteArray 导出的文件字节数据
     */
    @Override
    public void exportAttachment(String subject, String fromEmail, String toEmail, String bodyContent, String fileName, byte[] attachmentByteArray) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            mimeMessage.setFrom(fromEmail);
            mimeMessage.setRecipients(Message.RecipientType.TO, toEmail);
            mimeMessage.setSubject(subject);

            MimeMultipart contentMultipart = new MimeMultipart("mixed");
            // 创建附件
            MimeBodyPart excelBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachmentByteArray, "application/octet-stream");
            DataHandler dataHandler = new DataHandler(dataSource);
            excelBodyPart.setFileName(fileName);
            excelBodyPart.setDataHandler(dataHandler);

            // 正文内容
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setText(bodyContent);

            contentMultipart.addBodyPart(excelBodyPart);
            contentMultipart.addBodyPart(textBodyPart);
            mimeMessage.setContent(contentMultipart);
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new BizException("邮件发送失败");
        }
    }

Reproduced in: https: //www.jianshu.com/p/1cade1f2b11b

Guess you like

Origin blog.csdn.net/weixin_34387468/article/details/91061860