Created
August 11, 2011 13:47
-
-
Save guohai/1139699 to your computer and use it in GitHub Desktop.
为修复BUG快速写的一个读取邮件(eml)文件中附件名的代码片段,目前状态基本能用
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.xkit.mail.demo; | |
import java.io.UnsupportedEncodingException; | |
import java.net.URLDecoder; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class MailAttachmentFilenameDemo { | |
public static void main(String[] args) { | |
System.out | |
.println(decodeFilename( | |
"message/rfc822; name*0=\"16951479.5239.1308559950610.JavaMail.root@localhost.localdomain.e\"; name*1=\"ml\"", | |
"name", null, null)); | |
System.out | |
.println(decodeFilename( | |
"filename*0*=GB2312''%C1%D9%CA%B1%53%51%4C%A3%AC%D0%DE%B8%C4%C3%DC%C2%EB%B5;filename*1*=%C8%B5%C8", | |
"name", null, null)); | |
} | |
public static String decodeFilename(String fileNameStr, String field, | |
String encoding, String charset) { | |
Pattern pattern = Pattern.compile(("[\\s\\S]*" + field + "[\\s\\S]*$")); | |
StringBuilder nameBuilder = new StringBuilder(fileNameStr.length() / 3); | |
String[] names = fileNameStr.split(";"); | |
for (String name : names) { | |
String[] kvs = name.split("=", -1); | |
Matcher m = pattern.matcher(kvs[0]); | |
if (m.find()) { | |
String chunk = null; | |
// 获取编码 | |
String[] cv = kvs[1].split("''"); | |
if (2 == cv.length) { | |
charset = cv[0].trim(); | |
chunk = cv[1].trim(); | |
} else if (1 == cv.length) { | |
chunk = cv[0].trim(); | |
} | |
if (chunk.startsWith("\"")) { | |
chunk = chunk.replaceAll("^\"*", ""); | |
} | |
if (chunk.endsWith("\"")) { | |
chunk = chunk.replaceAll("\"*$", ""); | |
} | |
nameBuilder.append(chunk); | |
} | |
} | |
// 如果前后有双引号,去掉 | |
// 如果需要解码,解码 | |
String result = null; | |
if (null != charset) { | |
try { | |
result = URLDecoder.decode(nameBuilder.toString(), charset); | |
} catch (UnsupportedEncodingException e) { | |
result = nameBuilder.toString(); | |
e.printStackTrace(); | |
} | |
} else { | |
result = nameBuilder.toString(); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment