先从最棘手的来吧 1.如何正确显示邮件内容为中文明码而且Content-Type里没有指定charset的邮件 据我所知,新浪发出的邮件都是这样的,我的youmail里无法正确显示,为乱码.后来分析内容,才知道是他们的邮件里没有指定charset.. 邮件内容部分如: From: hrbtvu_ly <[email protected]> To: [email protected] Subject: 你好啊 MIME-Version: 1.0 Date: Thu, 11 Nov 2004 12:51:30 +0800 X-Mailer: SinaMail 3.0Beta (FireToad) X-Priority: 3 X-Antivirus-MYDOMAIN-1.22-st-qms: added fake Content-Type header Content-Type: text/plain
你好啊 ============end============== 可以看出连标题都是中文明码的,这个我后面讲到如何处理. 我的解决方法是:修改com.sun.mail.handlers.text_plain类的getCharset(),修改成: private String getCharset(String s) { try { ContentType contenttype = new ContentType(s); String s1 = contenttype.getParameter("charset"); if(s1 == null) s1 = "gb2312"; return MimeUtility.javaCharset(s1); } catch(Exception _ex) { return "gb2312"; } } 这是我认为最简单的办法了. 2.Subject或其他字段为中文明码的处理 这里我提供我写的一个方法,能够统一处理编码过的或者明文的字符串: /** * 返回解码后的字符串 */ public static String getDecodeText(String eword) { if (eword == null) return null; try { Pattern p = Pattern.compile("=\\?.+\\?="); Matcher m = p.matcher(eword); StringBuffer sb = new StringBuffer(); boolean result = m.find(); if (result) { while (result) { m.appendReplacement(sb, MimeUtility.decodeText(m.group())); result = m.find(); } m.appendTail(sb); return sb.toString(); } else { String decodevalue = new String(eword.getBytes("ISO8859-1"), "GBK"); return decodevalue; } } catch (Exception e) { e.printStackTrace(); return eword; } } 3.发送邮件中中文的处理 邮件标题: newmsg.setSubject(subject, "GBK"); 附件: BASE64Encoder enc = new BASE64Encoder(); mbp2.setFileName("=?GBK?B?" + enc.encode((new String(ai.getFileName()).getBytes("GBK"))) + "?="); 这只是给出一个方法,具体你还要自己改一改 内容:msg.setContent(body, "text/plain;charset=GBK"); 主要原则是处处指定charset
今天先说这么多了,有问题大家mailto:[email protected],或qq:100949955 
|