关于javamail读取中文路径和文件名乱码的问题

2025-01-19 16:11:36
推荐回答(2个)
回答1:

你的这行代码attachName=new String(attachName.getBytes("gb2312"),"ISO8859-1");应该修改成attachName=new String(attachName.getBytes("ISO8859-1"),"gb2312");还有就是邮件中文乱码问题。在界面传递时,中文通过一定编码格式编码后在传给另外一个界面,接收界面如果要正确的显示中文,应该正确的解码。可以使用jdk1.6提供MimeUtility类。将 FileDataSource fds=new FileDataSource(filename);修改为:
FileDataSource fds=new FileDataSource(MimeUtility.encodeText(filename));这样的话应该能解决附件乱码问题。这只是自己肤浅的认识,可能有些地方还有漏洞,往高手看后指点!!
=====================================================================
下面是敝人一段中文处理的代码,可以做参考
public class Demo3
{
/**
* 复杂邮件含附件+中文附件名_回信地址_友好名称
* @param args
*/
public static void main(String[] args) throws Exception
{

//配置环境
Properties pros = new Properties();
pros.setProperty("mail.smtp.auth", "true");
pros.setProperty("mail.transport.protocol", "smtp");
Session session = Session.getInstance(pros);
session.setDebug(true);
//创建卫星
Message msg = new MimeMessage(session);
//设置msg的一些信息--发件人、主题、内容..
msg.setFrom(new InternetAddress("\""+MimeUtility.encodeText("超越")+"\" "));
msg.setRecipients(RecipientType.TO,
InternetAddress.parse(MimeUtility.encodeText("毕老师")+" ,"+MimeUtility.encodeText("王老师")+" ")
);
msg.setReplyTo(InternetAddress.parse("ss@sohu.com"));

MimeMultipart bodyMultipart = new MimeMultipart("mixed");
msg.setContent(bodyMultipart);

MimeBodyPart appurt1 = new MimeBodyPart();
MimeBodyPart appurt2 = new MimeBodyPart();
MimeBodyPart contentPart = new MimeBodyPart();

bodyMultipart.addBodyPart(appurt1);
bodyMultipart.addBodyPart(appurt2);
bodyMultipart.addBodyPart(contentPart);

appurt1.setDataHandler(new DataHandler(new FileDataSource("")));
appurt1.setFileName("");//重要

appurt2.setDataHandler(new DataHandler(new FileDataSource("")));
appurt2.setFileName("");

MimeMultipart contentMultipart = new MimeMultipart("related");
contentPart.setContent(contentMultipart);

MimeBodyPart picPart = new MimeBodyPart();
MimeBodyPart htmlPart = new MimeBodyPart();
contentMultipart.addBodyPart(picPart);
contentMultipart.addBodyPart(htmlPart);

picPart.setDataHandler(new DataHandler(new FileDataSource("")));
picPart.setHeader("Content-Location", "www.sohu.com/log.jpg");
htmlPart.setText("图片", "text/html;charset=gbk");

msg.saveChanges();

//创建火箭
Transport transport = session.getTransport();
transport.connect("smtp.sina.com", 25, "hjflbc1990@sina.com", "*****");

//火箭发送卫星
transport.sendMessage(msg, InternetAddress.parse("aa,aaa"));

transport.close();
}
}

回答2:

fdss