简体   繁体   English

Java邮件charset ISO-8859-2无法正常工作

[英]Java mail charset ISO-8859-2 not working

I am having problem with Java Mail API. 我遇到Java Mail API问题。

I can successfully send mail, but some special characters (from ISO-8859-2 languages like czech, slovak) are not shown in mail. 我可以成功发送邮件,但是一些特殊字符(来自ISO-8859-2语言,如捷克语,斯洛伐克语)不会在邮件中显示。 They are damaged even in IDE output. 即使在IDE输出中它们也会损坏。

What am I doing wrong? 我究竟做错了什么?

Message msg = new MimeMessage(session);
msg.setContent(message, "text/plain; charset=iso-8859-2")

I found solution, using multipart. 我找到了解决方案,使用multipart。 here is code : 这是代码:

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
MimeMultipart multipart = new MimeMultipart();
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
MimeBodyPart tmpBp = new MimeBodyPart();
tmpBp.setContent(message,"text/plain; charset=utf-8");
multipart.addBodyPart(tmpBp);
msg.setContent(multipart);
Transport.send(msg);

msg.setContent(message, "text/plain; charset=UTF-8"); msg.setContent(message,“text / plain; charset = UTF-8”);

instead of the charset you've given? 而不是你给的charset?

Rather use UTF-8 as charset and configure your IDE console to use the very same charset as well. 而是使用UTF-8作为字符集,并将IDE控制台配置为使用完全相同的字符集。 I don't know which IDE you're using as you didn't tell about it, but if it were Eclipse, then you can change it by Window > Preferences > General > Workspace > Text file encoding > Other > UTF-8 . 我不知道你正在使用哪个IDE,因为你没有告诉它,但如果它是Eclipse,那么你可以通过Window > Preferences > General > Workspace > Text file encoding > Other > UTF-8来改变它。

If that doesn't fix the problem, then the problem lies somewhere else. 如果这不能解决问题,那么问题出在其他地方。 Maybe you're reading the message from a file using the wrong encoding. 也许您正在使用错误的编码从文件中读取消息。 For that you need to use InputStreamReader which takes the charset as 2nd constructor argument. 为此,您需要使用InputStreamReader ,它将charset作为第二个构造函数参数。

You should use the setText method from the class MimeMessage instead of setContent 您应该使用类MimeMessagesetText方法而不是setContent

/**
     * Convenience method that sets the given String as this part's
     * content, with a MIME type of "text/plain" and the specified
     * charset. The given Unicode string will be charset-encoded
     * using the specified charset. The charset is also used to set
     * the "charset" parameter.
     *
     * @param   text    the text content to set
     * @param   charset the charset to use for the text
     * @exception   MessagingException  if an error occurs
     */
    public void setText(String text, String charset)
            throws MessagingException {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM