Java 发送邮件Excel附件实现流程

本文将教你如何使用 Java 发送带有 Excel 附件的邮件。下面是整个实现流程的步骤表格:

步骤 动作
1 创建一个 Java 项目
2 导入所需的依赖包
3 配置邮件发送相关信息
4 创建 Excel 文件
5 将 Excel 文件作为附件添加到邮件中
6 发送邮件

现在,让我们逐步进行每个步骤的详细解释和代码实现。

1. 创建一个 Java 项目

首先,创建一个新的 Java 项目,并设置好相关的开发环境。

2. 导入所需的依赖包

在项目的依赖管理文件(例如 Maven 的 pom.xml)中,加入以下依赖:

<dependencies>
   <dependency>
       <groupId>javax.mail</groupId>
       <artifactId>javax.mail-api</artifactId>
       <version>1.6.2</version>
   </dependency>
   <dependency>
       <groupId>com.sun.mail</groupId>
       <artifactId>javax.mail</artifactId>
       <version>1.6.2</version>
   </dependency>
</dependencies>

这些依赖包是用于实现邮件发送功能的必需依赖。

3. 配置邮件发送相关信息

在 Java 代码中配置邮件发送的相关信息,包括 SMTP 服务器地址、端口号、发件人邮箱和密码等。示例代码如下:

public class MailConfig {
   private static final String SMTP_HOST = "smtp.gmail.com";
   private static final int SMTP_PORT = 587;
   private static final String USERNAME = "your-email@gmail.com";
   private static final String PASSWORD = "your-password";

   public static Properties getProperties() {
       Properties properties = new Properties();
       properties.put("mail.smtp.host", SMTP_HOST);
       properties.put("mail.smtp.port", SMTP_PORT);
       properties.put("mail.smtp.auth", "true");
       properties.put("mail.smtp.starttls.enable", "true");
       properties.put("mail.smtp.starttls.required", "true");
       return properties;
   }

   public static Session getSession() {
       return Session.getInstance(getProperties(), new Authenticator() {
           protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(USERNAME, PASSWORD);
           }
       });
   }
}

上述代码中,我们使用了 Gmail 的 SMTP 服务器作为示例。你需要将 USERNAMEPASSWORD 替换成你自己的真实邮箱地址和密码。

4. 创建 Excel 文件

在 Java 代码中,使用 Apache POI 库创建 Excel 文件。示例代码如下:

public class ExcelGenerator {
   public static void generateExcel() {
       Workbook workbook = new XSSFWorkbook();
       Sheet sheet = workbook.createSheet("Sheet1");

       Row headerRow = sheet.createRow(0);
       headerRow.createCell(0).setCellValue("Name");
       headerRow.createCell(1).setCellValue("Age");

       Row dataRow = sheet.createRow(1);
       dataRow.createCell(0).setCellValue("John");
       dataRow.createCell(1).setCellValue(30);

       try (FileOutputStream outputStream = new FileOutputStream("data.xlsx")) {
           workbook.write(outputStream);
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}

上述代码使用了 Apache POI 库创建了一个包含姓名和年龄信息的 Excel 文件,并将其保存为 data.xlsx

5. 将 Excel 文件作为附件添加到邮件中

在前面的步骤中,我们已经创建好了 Excel 文件。现在,我们需要将其作为附件添加到邮件中。示例代码如下:

public class MailSender {
   public static void sendMail() {
       Session session = MailConfig.getSession();
       try {
           Message message = new MimeMessage(session);
           message.setFrom(new InternetAddress(MailConfig.USERNAME));
           message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
           message.setSubject("Java Mail with Excel Attachment");

           MimeBodyPart messageBodyPart = new MimeBodyPart();
           messageBodyPart.setText("Please find the attached Excel file.");

           Multipart multipart = new MimeMultipart();
           multipart.addBodyPart(messageBodyPart);

           MimeBodyPart attachmentBodyPart = new MimeBodyPart();
           attachmentBodyPart.attachFile(new File("data.xlsx")); // 添加 Excel 附件

           multipart.addBodyPart(attachmentBodyPart);

           message.setContent(multipart);

           Transport.send(message);
       } catch (MessagingException | IOException e) {
           e.printStackTrace();
       }