简体   繁体   中英

Java mail charset ISO-8859-2 not working

I am having problem with 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. They are damaged even in IDE output.

What am I doing wrong?

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

I found solution, using 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");

instead of the charset you've given?

Rather use UTF-8 as charset and configure your IDE console to use the very same charset as well. 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 .

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.

You should use the setText method from the class MimeMessage instead of 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 {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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