解决JavaMail使用IMAP连接时BodyPart.getInputStream()返回空的文件流问题

需求:使用JavaMail获取邮件附件,并且下载

问题:在使用IMAP方式连接邮件服务器后,BodyPart.getInputStream()方法获取文件流确实空的,但是使用POP3的方式连接,却可以拿到文件流

解决方案:

增加配置:props.setProperty("mail.imap.partialfetch","false");

Properties props = new Properties();
props.setProperty("mail.imap.partialfetch","false");
//.....省略其他连接配置

参考文档:

JavaMail API - FAQ

JavaMail

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

涛哥是个大帅比

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值