Java发送以流的方式添加Excel附件并邮件发送

1. 简介

在实际开发中,我们经常需要通过邮件发送文件附件。本文将介绍如何使用Java发送带有Excel附件的邮件,并使用流的方式添加附件。

2. 准备工作

在开始之前,我们需要准备以下环境:

  • JDK 1.8 或更高版本
  • Apache POI 库用于操作Excel文件
  • JavaMail 库用于发送邮件

你可以通过Maven等构建工具来导入这些库。

3. 创建Excel文件

首先,我们需要创建一个Excel文件作为附件。本文以一个简单的学生信息表为例,创建一个Excel文件包含学生的姓名、年龄和成绩。

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class CreateExcel {
    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("学生信息表");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        Cell headerCell1 = headerRow.createCell(0);
        headerCell1.setCellValue("姓名");
        Cell headerCell2 = headerRow.createCell(1);
        headerCell2.setCellValue("年龄");
        Cell headerCell3 = headerRow.createCell(2);
        headerCell3.setCellValue("成绩");

        // 创建数据行
        Row dataRow = sheet.createRow(1);
        Cell dataCell1 = dataRow.createCell(0);
        dataCell1.setCellValue("张三");
        Cell dataCell2 = dataRow.createCell(1);
        dataCell2.setCellValue(18);
        Cell dataCell3 = dataRow.createCell(2);
        dataCell3.setCellValue(90);

        // 保存文件
        try (FileOutputStream outputStream = new FileOutputStream("学生信息表.xlsx")) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        workbook.close();
    }
}

运行以上代码,将会在项目根目录下生成一个名为“学生信息表.xlsx”的Excel文件。

4. 发送邮件

接下来,我们需要使用JavaMail库来发送邮件。以下是一个使用Gmail SMTP服务器发送邮件的例子。

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class SendEmail {
    public static void main(String[] args) {
        String host = "smtp.gmail.com";
        int port = 587;
        String username = "your-email@gmail.com";
        String password = "your-password";

        String toAddress = "recipient-email@example.com";
        String subject = "附件测试";
        String body = "这是一个带有Excel附件的测试邮件。";

        // 设置邮件属性
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);

        // 创建 Session 对象
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 创建邮件消息对象
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            message.setSubject(subject);

            // 创建邮件正文
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(body);

            // 创建附件
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.attachFile("学生信息表.xlsx");

            // 创建多部分消息
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);
            multipart.addBodyPart(attachmentPart);

            // 设置消息内容
            message.setContent(multipart);

            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功!");
        } catch (MessagingException | IOException e) {
            e.printStackTrace();
        }
    }
}

在以上代码中,请替换以下内容:

  • your-email@gmail.com:你的Gmail邮箱
  • your-password:你的邮箱密码
  • recipient-email@example.com:收件人邮箱地址

运行以上代码,将会发送一封带有Excel附件的测试邮件。

5. 流程图

下面是整个流程的流程图:

flowchart TD;

subgraph 准备工作
A(环境准备)
end

subgraph 创建Excel文件
B(创建Excel文件)
end

subgraph 发送邮件
C(设置邮件属性