我正在使用JavaMail 1.4.1从电子邮件帐户中读取消息(我已经升级到1.4.5版本,但存在相同的问题),但是内容编码存在问题:
POP3Message pop3message;
...
Object contentObject = pop3message.getContent();
...
String contentType = pop3message.getContentType();
String content = contentObject.toString();
某些消息可以正确读取,但是其他消息由于编码不正确而具有奇怪的字符。我已经意识到它不适用于特定的内容类型。
如果contentType是以下任意一种,则效果很好:
文本/纯文本; charset = ISO-8859-1
文本/纯文本;charset =“ iso-8859-1”
文本/纯文本;charset =“ ISO-8859-1”;format =“ flowed”
文本/纯文本; charset = windows-1252
但不是,如果不是:
- 文本/纯文本;charset =“ utf-8”
对于此contentType(UTF-8,如果我尝试获取编码(pop3message.getEncoding()),则得到]
quoted-printable
对于后一种编码,例如,我在调试器中获得了String值(以与保存对象后在数据库中看到的相同的方式):
Ubicación(代替Ubicación)
但是,如果我在浏览器中使用电子邮件客户端打开电子邮件,则可以毫无问题地读取它,并且它是正常的消息(没有附件,只有文本,因此该消息似乎还可以。
关于如何解决此问题的任何想法?
谢谢。
UPDATE这是我为尝试jlordo给定的功能getUTF8Content()添加的代码。
POP3Message pop3message = (POP3Message) message;
String uid = pop3folder.getUID(message);
//START JUST FOR TESTING PURPOSES
if(uid.trim().equals("1401")){
Object utfContent = pop3message.getContent();
System.out.println(utfContent.getClass().getName()); // it is of type String
//System.out.println(utfContent); // if not commmented it prints the content of one of the emails I'm having problems with.
System.out.println(pop3message.getEncoding()); //prints: quoted-printable
System.out.println(pop3message.getContentType()); //prints: text/plain; charset="utf-8"
String utfContentString = getUTF8Content(utfContent); // throws java.lang.ClassCastException: java.lang.String cannot be cast to javax.mail.util.SharedByteArrayInputStream
System.out.println(utfContentString);
}
//END TEST CODE
我正在使用JavaMail 1.4.1从电子邮件帐户中读取消息(我已经升级到1.4.5版本,但存在相同的问题),但是内容编码方面存在问题:POP3Message。 ..
您如何检测到这些消息具有“奇怪的字符”?您在某处显示数据吗?您用于显示数据的任何方法都可能无法正确处理Unicode字符。
尝试一下,让我知道它是否有效:
对我有用的是我叫getContentType()
,然后检查字符串中是否包含“ utf”(定义用作UTF的字符集。)
首先,您必须按照这种方式根据UTF-8编码添加标头: