如何在java springboot中通过电子邮件发送HSSF工作簿xls?

8wigbo56  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(357)

所以我有自己的javaspringboot代码,用本地目录中的列表编写excel电子表格。基本上,它只是获取我想要的目录中的文件列表,然后将目录中每个zip文件的内容列出到excel电子表格中。然后我使用fileoutputstream将xls生成到另一个目录中。代码类似于:

HSSFWorkbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("Test sheet");
/*
...
insert code to create the rows and cells of the workbook/sheet
...

* /

FileOutputStream fileOutputStream = new FileOutputStream("/test/random/excelspreadsheets")
workbook.write(fileOutputStream);
fileOutputStream.close();

所以这会写入xls,生成xls并将其保存到指定的目录中,但我的问题是,如何将其作为电子邮件发送,主题为cc,from,to,最重要的是作为电子邮件的附件发送到指定的“我的电子邮件”或“朋友的电子邮件”?在过去的一天里,我一直在为这件事挠头,也不知道,只是对我来说似乎很模糊。谢谢您!

uurv41yg

uurv41yg1#

首先添加此依赖项

<!-- Email -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
        <version>${spring.boot.version}</version>
    </dependency>

然后您可以使用以下服务发送此电子邮件

@Service
public class EmailService {
private JavaMailSender emailSender;

@Autowired
public EmailService(JavaMailSender emailSender) {
    this.emailSender = emailSender;
}

public void sendEmail() {

    String to = "recepient@gmail.com";
    String subject = "email subject";
    String text = "email text";

    MimeMessage message = emailSender.createMimeMessage();

    //TODO here convert your workbook to a xlsx file 
    File file = new File("yourFile.xlsx");
    if (file.exists() && !file.isDirectory()) {

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text);

            helper.addAttachment("yourFile.xlsx", file);
        } catch (Exception ex) {
        System.out.println("Error");
        }
    }

    emailSender.send(message);
}

相关问题