spring boot 中使用 POP3协议读取并解析邮件

spring boot 中使用 POP3协议读取并解析邮件

1.邮箱授权

QQ邮箱授权,打开 “设置” 切换到 “账户” 找到下图中设置,开启 “POP3/SMTP服务” 和 “IMAP/SMTP服务”,开启后获取的授权码记得保存后续会用到
在这里插入图片描述

2.导入maven 依赖
<!-- 邮件email -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.接收并解析邮件(POP3协议对应邮箱端口为 995)POP3协议与IMAP协议授权码不同

public class TestEmail {

public static void main(String[] args) throws Exception {

    POP3Store pop3Store = null;
    try {
        Session session = setCollectProperties();
        pop3Store = (POP3Store)session.getStore("pop3");
        pop3Store.connect("pop.qq.com", 995, "邮箱账号", "授权码");
        POP3Folder pop3Folder = (POP3Folder) pop3Store.getFolder("INBOX");
        pop3Folder.open(Folder.READ_WRITE); //打开收件箱
        FetchProfile fetchProfile = new FetchProfile();
        fetchProfile.add(FetchProfile.Item.ENVELOPE);
        FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN),false);
        Message [] messages = pop3Folder.search(flagTerm);
        pop3Folder.fetch(messages,fetchProfile);
        int length = messages.length;
        System.out.println("收件箱的邮件数:" + length);
        Folder folder = pop3Folder.getStore().getDefaultFolder();
        Folder[] folders = folder.list();

        for (int i = 0; i < folders.length; i++) {
            System.out.println("名称:"+folders[i].getName());
        }

        for (int i = 0; i < length; i++) {
            MimeMessage msg = (MimeMessage) messages[i];
            String from = MimeUtility.decodeText(messages[i].getFrom()[0].toString());
            InternetAddress ia = new InternetAddress(from);
            System.out.println("发件人:" + ia.getPersonal() + '(' + ia.getAddress() + ')');
            System.out.println("主题:" + messages[i].getSubject());
            System.out.println("邮件发送时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(messages[i].getSentDate()));
            boolean isContainerAttachment = isContainAttachment(msg);
            System.out.println("是否包含附件:" + isContainerAttachment);
            if (isContainerAttachment) {
                 //设置需要保存的目录并保存附件
                saveAttachment(msg, "F:\\test\\"+msg.getSubject() + "_"+i+"_"); //保存附件
            }
            messages[i].setFlag(Flags.Flag.SEEN, true);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(pop3Store != null){
            pop3Store.close();
        }
    }
}

/**
 * 设置连接邮箱属性
 * @return
 * @throws GeneralSecurityException
 */
private static Session setCollectProperties() throws GeneralSecurityException {
    Properties props = new Properties();
    props.setProperty("mail.popStore.protocol", "pop3");       // 使用pop3协议
    props.setProperty("mail.pop3.port", "995");           // 端口

    MailSSLSocketFactory sf = new MailSSLSocketFactory();
    sf.setTrustAllHosts(true);
    props.put("mail.pop3.ssl.enable",true);
    props.put("mail.pop3.ssl.socketFactory",sf);
    props.setProperty("mail.pop3.host", "pop.qq.com");


    return Session.getInstance(props);
}

/**
 * 判断邮件中是否包含附件
 * @param
 * @return 邮件中存在附件返回true,不存在返回false
 * @throws MessagingException
 * @throws Exception
 */
public static boolean isContainAttachment(Part part) throws Exception {
    boolean flag = false;
    if (part.isMimeType("multipart/*")) {
        MimeMultipart multipart = (MimeMultipart) part.getContent();
        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            String disp = bodyPart.getDisposition();
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                flag = true;
            } else if (bodyPart.isMimeType("multipart/*")) {
                flag = isContainAttachment(bodyPart);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("application") != -1) {
                    flag = true;
                }

                if (contentType.indexOf("name") != -1) {
                    flag = true;
                }
            }

            if (flag) break;
        }
    } else if (part.isMimeType("message/rfc822")) {
        flag = isContainAttachment((Part)part.getContent());
    }
    return flag;
}

/**
 * 保存附件
 * @param part 邮件中多个组合体中的其中一个组合体
 * @param destDir  附件保存目录
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void saveAttachment(Part part, String destDir) throws Exception{
    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 disp = bodyPart.getDisposition();
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                InputStream is = bodyPart.getInputStream();
                saveFile(is, destDir, decodeText(bodyPart.getFileName()));
            } else if (bodyPart.isMimeType("multipart/*")) {
                saveAttachment(bodyPart,destDir);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                }
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(),destDir);
    }
}

/**
 * 读取输入流中的数据保存至指定目录
 * @param is 输入流
 * @param fileName 文件名
 * @param destDir 文件存储目录
 * @throws Exception
 */
private static void saveFile(InputStream is, String destDir, String fileName)
        throws Exception {
    //如果文件名称包含关键字则进行保存
    BufferedInputStream bis = new BufferedInputStream(is);
    BufferedOutputStream bos = new BufferedOutputStream(
            new FileOutputStream(new File(destDir + fileName)));
    int len = -1;
    while ((len = bis.read()) != -1) {
        bos.write(len);
        bos.flush();
    }
    bos.close();
    bis.close();
}

/**
 * 文本解码
 * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
 * @return 解码后的文本
 * @throws UnsupportedEncodingException
 */
public static String decodeText(String encodeText) throws UnsupportedEncodingException {
    if (encodeText == null || "".equals(encodeText)) {
        return "";
    } else {
        return MimeUtility.decodeText(encodeText);
    }
}
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,Spring Boot 可以使用 JavaMail API 来读取 IMAP 邮件的附件。你需要使用 JavaMail API 的 IMAP 协议实现来连接到邮件服务器,并使用 JavaMail API 的 MimeMessage 类来处理邮件和附件。 以下是一个基本示例代码,展示如何使用 Spring Boot 和 JavaMail API 从 IMAP 邮箱读取邮件和附件: ```java @Component public class EmailReceiver { @Autowired private JavaMailSender emailSender; @Scheduled(fixedDelay = 60000) public void receiveEmail() throws MessagingException, IOException { Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getInstance(props, null); Store store = session.getStore(); store.connect("imap.gmail.com", "your_email@gmail.com", "your_password"); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Message[] messages = inbox.getMessages(); for (Message message : messages) { if (message.getContent() instanceof Multipart) { Multipart multipart = (Multipart) message.getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) { continue; } InputStream inputStream = bodyPart.getInputStream(); // process the attachment inputStream here } } } inbox.close(false); store.close(); } } ``` 在上面的示例代码,我们通过 JavaMail API 的 IMAP 协议实现连接到 Gmail 邮箱,并在收件箱遍历每个邮件。如果邮件是多部分 MIME 类型(即包含附件),我们就遍历每个邮件部分并检查是否有附件。如果找到了附件,我们就可以使用 `bodyPart.getInputStream()` 方法获取附件的输入流,并在此处处理附件数据。 注意,在使用 JavaMail API 时,你需要提供正确的邮件服务器地址、用户名和密码,以及必要的协议和端口号。此外,你还需要处理可能出现的异常,例如邮件服务器连接错误和附件读取错误等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值