解决javamail,接收gb2312乱码问题

最近用javamail读取邮件,由于实际使用的用户,有台湾的、香港等地区,导致文本出现了乱码。主要是字符集gb2312,我们系统用的是utf-8的。

为了解决这个问题,重写了javaee下的类,一个是subject,一个是content。

标题重写如下:

import java.io.UnsupportedEncodingException;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;


public class MimeMessageNew extends MimeMessage {

public static String charset_gb2312 = "?gb2312?";


public MimeMessageNew(MimeMessage message) throws MessagingException {
super(message);
}


@Override
public String getSubject() throws MessagingException {
String rawvalue = getHeader("Subject", null);
if (rawvalue == null)
return null;

if(rawvalue.contains(charset_gb2312)) {
rawvalue.replace("?gb2312?", "?gbk?");
try {
return MimeUtility.decodeText(MimeUtility.unfold(rawvalue));
}catch (UnsupportedEncodingException ex) {

}
return rawvalue;
}else {
return super.getSubject();
}
}
}

使用方法:new MimeMessageNew(msg).getSubject(); //MimeMessage msg = (MimeMessage) messages[i];


内容gb2312转utf8 代码如下:



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;


import org.apache.commons.lang3.StringUtils;


public class MimeBodyPartNew extends MimeBodyPart {


private BodyPart bodyPart;

public MimeBodyPartNew(BodyPart bodyPart) {
this.bodyPart = bodyPart;
}


@Override
public String getContent() throws IOException, MessagingException {
String content = (String)bodyPart.getContent();
         String[] s =  bodyPart.getHeader("Content-Type");
    if(s.length>0&&s[0].contains("GB2312")) {
    InputStream in = bodyPart.getInputStream();
    StringBuffer sb = new StringBuffer();
    String value = null;
    try {
                 InputStreamReader isr=new InputStreamReader(in,"gbk");
                 BufferedReader br=new BufferedReader(isr);
                 while(StringUtils.isNotEmpty(value = br.readLine())){  
                sb.append(value);
                 }  
                 isr.close();
                 content = sb.toString();
    }catch (Exception e) {
    e.printStackTrace();
    in.close();
    }
    }
return content;
}
}


使用方法:MimeBodyPartNew partNew = new MimeBodyPartNew(part);   //final BodyPart part = multipart.getBodyPart(i);
                    String content = partNew.getContent();

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值