我的邮件程序附件名不乱码截断程序给你
for (int i = 0; i < fileAttachment.size(); i++) {// 向Multipart添加附件
FileDataSource fds = (FileDataSource) fileAttachment.get(i);
MimeBodyPart attachFile = new MimeBodyPart();
attachFile.setDataHandler(new DataHandler(fds));
if (MailToolUtil.isHasContainStr(fds.getName()))
attachFile.setFileName("=?GBK?B?"
+ MailToolUtil.base64Encoder(fds.getName())
+ "?=");// 解决附件名中文乱码
else
attachFile.setFileName(fds.getName());
mp.addBodyPart(attachFile);
}
/**
* 是否还有中文字符串
*
* @param str
* @return
*/
public static boolean isHasContainStr(String str) {
if (str == null || str.length() == gbkToIso(str).length())
return false;
return true;
}
/**
* 将GBK转化为ISO-8859-1
*
* @param para
* @return
*/
public static String gbkToIso(String para) {
try {
return new String(para.getBytes("GBK"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
return "";
} catch (Exception e) {
return "";
}
}
/**
* BASE64Encoder编码
*
* @param str
* @return
*/
public static String base64Encoder(String str) {
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
return enc.encode(str.getBytes());
}
for (int i = 0; i < fileAttachment.size(); i++) {// 向Multipart添加附件
FileDataSource fds = (FileDataSource) fileAttachment.get(i);
MimeBodyPart attachFile = new MimeBodyPart();
attachFile.setDataHandler(new DataHandler(fds));
if (MailToolUtil.isHasContainStr(fds.getName()))
attachFile.setFileName("=?GBK?B?"
+ MailToolUtil.base64Encoder(fds.getName())
+ "?=");// 解决附件名中文乱码
else
attachFile.setFileName(fds.getName());
mp.addBodyPart(attachFile);
}
/**
* 是否还有中文字符串
*
* @param str
* @return
*/
public static boolean isHasContainStr(String str) {
if (str == null || str.length() == gbkToIso(str).length())
return false;
return true;
}
/**
* 将GBK转化为ISO-8859-1
*
* @param para
* @return
*/
public static String gbkToIso(String para) {
try {
return new String(para.getBytes("GBK"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
return "";
} catch (Exception e) {
return "";
}
}
/**
* BASE64Encoder编码
*
* @param str
* @return
*/
public static String base64Encoder(String str) {
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
return enc.encode(str.getBytes());
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货