【JAVA】将文件添加为附件并发送邮件

要将 Excel 文件添加为邮件附件并发送,使用 JavaMail API 和 Apache POI 库来实现。代码片段如下,演示如何将 Excel 文件添加为附件并发送邮件:

package com.jeeplus.sbptapi.upload.task;


import cn.hutool.extra.spring.SpringUtil;
import com.jeeplus.quartz.domain.ScheduleJob;
import com.jeeplus.quartz.domain.Task;
import com.jeeplus.sbptapi.jkapi.service.SbptDataUploadApiService;
import com.jeeplus.sbptapi.upload.service.dto.UploadResultsDTO;
import com.jeeplus.sys.domain.SysConfig;
import com.jeeplus.sys.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.factory.annotation.Autowired;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Properties;

/**
 * 定时通过邮箱反馈上传结果
 */
@Slf4j
@DisallowConcurrentExecution
public class DataUploadResultsTask extends Task {
    @Autowired
    private SbptDataUploadApiService sbptDataUploadApiService;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");

    /**
     * 30分钟执行一次
     * 定时执行上传接口
     */
//    @Scheduled(cron="0 1 * * * ?")
    @Override
    public void run(ScheduleJob scheduleJob) {
        try {
            List<UploadResultsDTO> uploadResults = sbptDataUploadApiService.getUploadResults();
            // 创建Excel文件
            String filePath = "上报结果报告.xlsx";
            createExcel(uploadResults, filePath);

            // 发送邮件
            String toEmail = scheduleJob.getRemarks(); // 收件人
            String subject = "上报结果报告"; // 邮件标题
            sendEmailWithAttachment(toEmail, subject, filePath);
        } catch (Exception e) {
            e.getMessage();
        }
    }


    /**
     * 获取结果数据
     * @param dataList  结果数据
     * @param filePath  文件信息
     * @throws IOException
     */
    public static void createExcel(List<UploadResultsDTO> dataList, String filePath) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Data");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("GS");
        headerRow.createCell(1).setCellValue("RQ");
        headerRow.createCell(2).setCellValue("FWZT");
        // ...

        // 写入数据
        int rowNum = 1;
        for (UploadResultsDTO data : dataList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(data.getGs());
            row.createCell(1).setCellValue(data.getRq());
            row.createCell(2).setCellValue(data.getFwzt());
        }

        // 保存Excel文件
        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            workbook.write(outputStream);
        }
    }


    /**
     *  发送邮件
     * @param toEmail           收件人
     * @param subject           邮件标题
     * @param attachmentPath    附件
     */
    public static void sendEmailWithAttachment(String toEmail, String subject, String attachmentPath) {
        SysConfig config = SpringUtil.getBean(SysConfigService.class).getById("1");
        String from = config.getMailName(); // 发件人
        String host = config.getSmtp(); // 邮箱服务器地址
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");


        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, config.getMailPassword());
            }
        });


        File attachment = new File(attachmentPath);
        
        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            mimeMessage.setSubject(subject);

            // 创建邮件附件
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.attachFile(attachment);

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

            // 设置邮件内容
            mimeMessage.setContent(multipart);


            Transport.send(mimeMessage);
            System.out.println("发送邮件成功");

        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 删除临时文件
            attachment.delete();
        }
    }

}

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值