【JAVA】javaMail附件名超过60显示错误

javaMail是我们java开发中常用的发邮件方式,但是会有某些

现象

附件名称无法正常展示,出现如:untitled,bat等不正确文件名。

分析

if (value.length() > 60 &&
				splitLongParameters && encodeParameters) {
		    int seg = 0;
		    name += "*";
		    while (value.length() > 60) {
			sb.addNV(name + seg, quote(value.substring(0, 60)));
			value = value.substring(60);
			seg++;
		    }
		    if (value.length() > 0)
			sb.addNV(name + seg, quote(value));
		} else {
		    sb.addNV(name, quote(value));
		}
	    }
        }

类的位置:javax.mail.internet.ParameterList#toString(int)

编码后的文件名长度超过60之后,并且splitLongParameters=true,encodeParameters=true的情况下或进行切断,导致文件名异常。

private static final boolean encodeParameters =
	PropUtil.getBooleanSystemProperty("mail.mime.encodeparameters", true);
private static final boolean splitLongParameters = 
	PropUtil.getBooleanSystemProperty(
	    "mail.mime.splitlongparameters", true);

在没有设置mail.mime.splitlongparameters相应值的情况下,默认值为true,并且一经初始化不可再被修改,导致后续即使指定该值为false依然无效,最终文件名超长被截断。

解决方案

在项目启动是添加参数初始化该值

//解决附件名不能过长的问题
System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
SpringApplication.run(AccountApplication.class, args);

这样写的原因:

  1. 保证在项目启动之后,该参数就被指定,避免启动之后某些操作提前初始化splitLongParameters=true。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,Spring Boot 中可以使用 JavaMail API 来读取 IMAP 邮件的附件。你需要使用 JavaMail API 的 IMAP 协议实现来连接到邮件服务器,并使用 JavaMail API 的 MimeMessage 类来处理邮件和附件。 以下是一个基本示例代码,展示如何使用 Spring BootJavaMail 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、付费专栏及课程。

余额充值