How to send a file via email without storing it in storage first using spring boot?

huangapple go评论58阅读模式
英文:

How to send a file via email without storing it in storage first using spring boot?

问题

我正在开发一个Spring Boot应用程序。在我的项目中,我正在创建一个 .xlsx 文件,然后我需要使用 Spring Boot 通过电子邮件发送它。

我可以使用 Apache POI 创建文件,但是后来要将其作为附件通过邮件发送,我应该将文件保存在本地的某个位置,然后在发送附件时将文件移回来。

是否有任何方式可以直接创建 .xlsx 文件并通过电子邮件发送它,而无需先将其保存在某个地方?

对于邮件部分,我使用的是 'org.springframework.boot:spring-boot-starter-mail'

对于 .xlsx 文件部分,我使用的是 'org.apache.poi', name: 'poi', version: '4.1.2''org.apache.poi', name: 'poi-ooxml', version: '4.1.2'

源代码:

public void test() throws IOException, MessagingException {
    XSSFWorkbook workbook = new XSSFWorkbook();
    List<String> s = Arrays.asList("person", "animal");
    CellStyle style = workbook.createCellStyle();
    style.setWrapText(true);
    int n = 1;
    String source = s.get(0);
    Sheet sheet = workbook.createSheet(source);
    for (String i : s) {
        if (!source.equalsIgnoreCase(i)) {
            sheet = workbook.createSheet(i);
            Row header = sheet.createRow(0);

            CellStyle headerStyle = workbook.createCellStyle();

            XSSFFont font = workbook.createFont();
            font.setFontName("Arial");
            font.setBold(true);
            headerStyle.setFont(font);

            Cell headerCell = header.createCell(0);
            headerCell.setCellValue("Name");
            headerCell.setCellStyle(headerStyle);

            headerCell = header.createCell(1);
            headerCell.setCellValue("Age");
            headerCell.setCellStyle(headerStyle);
            source = i;
        }

        Row row = sheet.createRow(n);
        Cell cell = row.createCell(0);
        cell.setCellValue("Udhav Mohata");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue(22);
        cell.setCellStyle(style);
        n++;
    }

    FileOutputStream outputStream = new FileOutputStream(Path_to_the_file);
    workbook.write(outputStream);
    workbook.close();
    sendMail();
}

public void sendMail() throws MessagingException, IOException {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom("spidercodie@gmail.com");
    helper.setTo("udhavmohata1@gmail.com");
    helper.setSubject("Test Mail");
    helper.setText("Hello world");
    FileSystemResource file = new FileSystemResource(path_to_the_file);
    helper.addAttachment("Invoice.xlsx", file);
    mailSender.send(message);
}
英文:

I am working on a spring boot application. In my project I am creating a .xlsx file and then i have to send via email using spring boot.

I am able to create the file using apache poi but later to send it via mail as an attachment, i should save the file somewhere in local and then move the file back in while sending it as an attachment.

Is there any way in which I can create a .xlsx file and directly send it via email, without saving it somewhere first?

For mail I am using 'org.springframework.boot:spring-boot-starter-mail'

For .xlsx I am using 'org.apache.poi', name: 'poi', version: '4.1.2' and 'org.apache.poi', name: 'poi-ooxml', version: '4.1.2'.

Source Code

       XSSFWorkbook workbook = new XSSFWorkbook();
List&lt;String&gt; s = Arrays.asList(&quot;person&quot;,&quot;animal&quot;);
CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
int n = 1;
String source = s.get(0);
Sheet sheet = workbook.createSheet(source);
for (String i : s) {
if(!source.equalsIgnoreCase(i)) {
sheet = workbook.createSheet(i);
Row header = sheet.createRow(0);
CellStyle headerStyle = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setFontName(&quot;Arial&quot;);
font.setBold(true);
headerStyle.setFont(font);
Cell headerCell = header.createCell(0);
headerCell.setCellValue(&quot;Name&quot;);
headerCell.setCellStyle(headerStyle);
headerCell = header.createCell(1);
headerCell.setCellValue(&quot;Age&quot;);
headerCell.setCellStyle(headerStyle);
source = i;
}
Row row = sheet.createRow(n);
Cell cell = row.createCell(0);
cell.setCellValue(&quot;Udhav Mohata&quot;);
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue(22);
cell.setCellStyle(style);
n++;
}
FileOutputStream outputStream = new FileOutputStream(Path_to_the_file);
workbook.write(outputStream);
workbook.close();
sendMail();
}
public void sendMail() throws MessagingException, IOException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(&quot;spidercodie@gmail.com&quot;);
helper.setTo(&quot;udhavmohata1@gmail.com&quot;);
helper.setSubject(&quot;Test Mail&quot;);
helper.setText(&quot;Hello world&quot;);
FileSystemResource file = new FileSystemResource(path_to_the_file));
helper.addAttachment(&quot;Invoice.xlsx&quot;, file);
mailSender.send(message);
}
</details>
# 答案1
**得分**: 5
这是我的建议,基于我提供的链接中的方法,这本质上也是Gagravarr在他的评论中提到的。
(这个方法在我使用Gmail时有效。)
**创建Excel文件**
我使用了您的代码,除了最后一部分。我没有将您的工作簿写入文件系统,而是通过`java.io.ByteArrayOutputStream`将其写入字节数组。
```java
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
workbook.write(bos);
} finally {
bos.close();
}
byte[] excelFileAsBytes = bos.toByteArray();

使用我的字节数组作为附件

在我的邮件代码中(几乎与您的代码相同,但我不想意外复制/粘贴您的电子邮件地址),我替换了这些行:

FileSystemResource file = new FileSystemResource(path_to_the_file));
helper.addAttachment("Invoice.xlsx", file);

使用org.springframework.core.io.ByteArrayResource的以下行:

ByteArrayResource resource = new ByteArrayResource(excelFileAsBytes);
helper.addAttachment("Invoice.xlsx", resource);

这样就会得到一封包含Excel文件附件的电子邮件。

英文:

Here is my suggestion, based on the approach in the link I provided - which is essentially what Gagravarr also mentioned in his comments.

(This approach works fine for me, using gmail.)

Creating the Excel File

I used your code, except for the final part. Instead of writing your workbook to the filesystem, I wrote it to a byte array via java.io.ByteArrayOutputStream.

ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
workbook.write(bos);
} finally {
bos.close();
}
byte[] excelFileAsBytes = bos.toByteArray();

Using my Byte Array as an Attachment

In my e-mailer code (which is almost identical to yours, but I did not want to copy/paste your e-mail address by accident), I replaced these lines:

FileSystemResource file = new FileSystemResource(path_to_the_file));
helper.addAttachment(&quot;Invoice.xlsx&quot;, file);

with these lines, using a org.springframework.core.io.ByteArrayResource:

ByteArrayResource resource = new ByteArrayResource(excelFileAsBytes);
helper.addAttachment(&quot;Invoice.xlsx&quot;, resource);

That gives me an e-mail containing the Excel file as an attachment.

huangapple
  • 本文由 发表于 2020年9月28日 21:07:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64102830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定