简体   繁体   English

Java邮件编码非英文字符

[英]Java mail encoding non english characters

Using the code below i can send an email written in non-english and although the subject appears correctly the body appears as gibberish. 使用下面的代码,我可以发送一封非英语的电子邮件,虽然主题正确显示,但正文显示为乱码。
Any ideas? 有任何想法吗?
Thank you 谢谢

public void postMail(String recipient, String subject, String message, String from) throws MessagingException, UnsupportedEncodingException {

            //Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", "mail.infodim.gr");

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);

            // create a message
            Message msg = new MimeMessage(session);

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress(from);
            msg.setFrom(addressFrom);

            InternetAddress addressTo=new InternetAddress(recipient);
            msg.setRecipient(Message.RecipientType.TO, addressTo);

            // Setting the Subject and Content Type
            msg.setSubject(subject);

            msg.setContent(message, "text/plain");
            Transport.send(msg);

        }

Try: 尝试:

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

Edit Changed to text/plain . 编辑已更改为text/plain

Instead of 代替

msg.setContent(message, "text/plain");

I would write 我会写的

Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(message, "text/plain; charset=ISO-8859-7");
mp.addBodyPart(mbp);

msg.setContent(mp);

I guessed ISO-8859-7 from your name because this charset is for Greek, but maybe you can choose it more properly. 我从你的名字中猜到了ISO-8859-7 ,因为这个charset是希腊语,但也许你可以更恰当地选择它。 Or maybe also UTF-8 works for your case. 或者也许UTF-8适用于您的情况。

If nothing else helps, try changing an encoding of your source files (including .java files) to UTF8. 如果没有其他帮助,请尝试将源文件(包括.java文件)的编码更改为UTF8。 In Eclipse it is done via Window -> Preferences -> General -> Workspace : Text file encoding I had CP1252 as a default for my text files. 在Eclipse中,它通过Window - > Preferences - > General - > Workspace:Text file encoding完成,我将CP1252作为文本文件的默认值。

I am getting my text from .properties files. 我从.properties文件中获取文本。 Changing them to UTF8 didn't help. 将它们更改为UTF8并没有帮助。 This is insane, but switching my .java files to UTF8 solved my issue! 这很疯狂,但将我的.java文件切换为UTF8解决了我的问题!

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

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