日期:2014-05-20  浏览次数:20646 次

java mail 附件名乱码
我用java mail写了一个收发邮件的,在发邮件时邮件符件名用的是GBK编码,能发出去,可是收着都是乱码,试过用OuoLook,Foxmail收都是乱码,高手门出来帮帮我.
代码如下:
发邮件:
(在调用startSend时对附件名进行了GBK编码)
public boolean startSend() {

//创建Properties对象
Properties props = System.getProperties();
//创建信件服务器
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", this.host);
props.put("mail.smtp.auth", "true"); //通过验证
//得到默认的对话对象
Session session = Session.getInstance(props);
try {
//创建一个消息,并初始化该消息的各项元素
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(this.from));
//收件人
if (this.to.trim().length() > 0) {  
String[] arr = this.to.split(",");
int receiverCount = arr.length;
if (receiverCount > 0) {
InternetAddress[] address = new InternetAddress[receiverCount];
for (int i = 0; i < receiverCount; i++) {
address[i] = new InternetAddress(arr[i]);
}
msg.addRecipients(Message.RecipientType.TO,address);
}
}
//抄送
if (this.cc.trim().length() > 0) {
String[] arr = this.cc.split(",");
//int ReceiverCount=1;
int receiverCount = arr.length;
if (receiverCount > 0) {
InternetAddress[] address = new InternetAddress[receiverCount];
for (int i = 0; i < receiverCount; i++) {
address[i] = new InternetAddress(arr[i]);
}
msg.addRecipients(Message.RecipientType.CC,address);
}
}
/**密送
if (this.bcc.trim().length() > 0) {
String[] arr = this.bcc.split(",");
//int ReceiverCount=1;
int receiverCount = arr.length;
if (receiverCount > 0) {
InternetAddress[] address = new InternetAddress[receiverCount];
for (int i = 0; i < receiverCount; i++) {
address[i] = new InternetAddress(arr[i]);
}
msg.addRecipients(Message.RecipientType.BCC,address);
}
}*/
msg.setSubject(subject);
//后面的BodyPart将加入到此处创建的Multipart中
Multipart mp = new MimeMultipart();  
//获取附件
int FileCount = this.arrFileName.getItemCount();
if (FileCount > 0) {
for (int i = 0; i < FileCount; i++) {
MimeBodyPart mbp = new MimeBodyPart();  
//选择出附件名
fileName = arrFileName.getItem(i).toString();
try{
fileName = MimeUtility.encodeText(arrFileName.getItem(i).toString());
if (fileName.startsWith("=?")) {
fileName = MimeUtility.decodeText(fileName);
}
}catch(Exception e){
System.out.println("getpart(int i)重新生成文件:"+e.toString());
}
//得到数据源
FileDataSource fds = new FileDataSource(fileName);
//得到附件本身并至入BodyPart
mbp.setDataHandler(new DataHandler(fds));
//得到文件名同样至入BodyPart
mbp.setFileName(fds.getName());
mp.addBodyPart(mbp);
}
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(this.body);
mp.addBodyPart(mbp);
//移走集合中的所有元素
arrFileName.removeAll();
//Multipart加入到信件
msg.setContent(mp);
} else {
//设置邮件正文
msg.setText(this.body);
}
//设置信件头的发送日期
msg.setSentDate(new Date());
msg.saveChanges();
//发送信件
Transport transport = session.getTransport("smtp");
transport.connect(this.host, this.userName, this.password);
if(this.to!=null && !this.to.trim().equals("")){