java读取邮件附件

前言

项目中会遇到读取邮件excel附件的信息至后台,下面分享一个java读取excel附件的方法。

1、要在后台中读取邮箱附件邮箱必须开启IMAP服务,下图示例为QQ邮箱开启对应服务的设置方法(其他邮箱也可找到对应的设置):

在这里插入图片描述

按照提示开通对应服务,需要注意的是如果邮箱使用的是授权码,则需要在后续使用时用授权码代替密码,授权码授权方式更为安全。

2、添加依赖

收发邮件依赖jakarta.mail

<dependency>
  <groupId>com.sun.mail</groupId>
  <artifactId>jakarta.mail</artifactId>
  <version>{version}</version>
</dependency>

读取execel文件依赖POI

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>{version}</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>{version}</version>
</dependency>
3、读取接收到的邮件,并读取附件信息
3.1读取接收到的邮件代码:
//设置邮箱服务器地址、端口、用户
Properties props = new Properties();
props.setProperty("mail.imapStore.protocol","imap");
props.setProperty("mail.imap.host", "邮箱服务器host");
props.setProperty("mail.imap.port","邮箱服务端口");
// 是否启用ssl
if (useSsl.equals(1)) {
  MailSSLSocketFactory sf = new MailSSLSocketFactory();
  sf.setTrustAllHosts(true);
  props.put("mail.imap.ssl.enable", true);
  props.put("mail.imap.ssl.socketFactory", sf);
  props.put("mail.imap.ssl.protocols", "TLSv1.2");
}
Session session = Session.getInstance(props);
IMAPStore imapStore = (IMAPStore) session.getStore("imap");
// 输入邮箱及密码(授权码)
imapStore.connect("邮箱服务器host", "邮箱服务端口", "email地址","email密码(授权码)");
//打开收件箱
IMAPFolder imapFolder = (IMAPFolder) imapStore.getFolder("INBOX");
if (!imapFolder.isOpen()) {
   imapFolder.open(Folder.READ_ONLY);
}
//读取指定时间之后的邮件数据
SearchTerm searchTerm = new ReceivedDateTerm(ComparisonTerm.GT, new Date(时间戳));
// 取到文件夹中所有信息
Message[] messages = imapFolder.search(searchTerm);
// 循环处理读取到的邮件信息
for (Message message : messages) {
   // 读取附件
   readAttachment(message )   
}
3.2读取附件并且缓存代码:
public List<EmailAttachmentPojo> readAttachment(Part part) throws Exception {
        List<EmailAttachmentPojo> bodyParts = new LinkedList<>();
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
            //复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                // 获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                // 某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disposition = bodyPart.getDisposition();
                if (disposition != null && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE))) {
                    bodyParts.add(EmailAttachmentPojo.builder()
                            .bodyPart(bodyPart)
                            .filename(decodeText(bodyPart.getFileName()))
                            .build());
                } else if (bodyPart.isMimeType("multipart/*")) {
                    bodyParts.addAll(readAttachment(bodyPart));
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.contains("name") || contentType.contains("application")) {
                        bodyParts.add(EmailAttachmentPojo.builder()
                                .bodyPart(bodyPart)
                                .filename(decodeText(bodyPart.getFileName()))
                                .build());
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            bodyParts.addAll(readAttachment((Part) part.getContent()));
        }
        return bodyParts;
}
3.3读取附件excel里的内容

使用POI读取excel的步骤:

1.创建工作簿

2.获取工作表

3.遍历工作表获得行对象

4.遍历行对象获取单元格对象

5.获得单元格中的值

读取excel内容代码示例:

// 1.获取工作簿
XSSFWorkbook workbook = new XSSFWorkbook("C:\\Users\\ghost\\Desktop\\hello.xlsx");
// 2.获取工作表
// xlsx第一个工作簿(Sheet1),下标从0开始,0就是第一个
XSSFSheet sheet = workbook.getSheetAt(0);
// 开始索引(0) 结束索引
int lastRowNum = sheet.getLastRowNum(); //行的结束索引
for (int i = 0; i <= lastRowNum; i++) {
	// 拿到行
	XSSFRow row = sheet.getRow(i);
	if (row != null){
		short cellNum = row.getLastCellNum(); //单元格的结束索引
		for (int j = 0; j <= cellNum; j ++){
			XSSFCell cell = row.getCell(j);
			// 单元格不为空就去拿他的值
			if (cell != null){
				String stringCellValue = cell.getStringCellValue();
				System.out.println(stringCellValue);
			}
		}
	}
}
// 释放资源
workbook.close();

基于上述读取邮件和读取excel文件的方法就可以从邮箱中获取到所需要的业务数据。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值