Java Mail API - 编码问题 [英] Java Mail API - Encoding problems
问题描述
我正在使用 Java 邮件 API,并且正在尝试通过 Gmail 的 SMTP 发送电子邮件.我的程序如何工作:java.util.Scanner 类用于获取用户输入 - 我向用户询问要在邮件发送类中使用的各种参数;它执行以下操作:
I'm using Java Mail API and I'm trying to send an email through Gmail's SMTP. How my program works: java.util.Scanner class is used to get user input - I'm asking user for various parameters to be used in mail sending class; which does the following:
Message mailMessage = new MimeMessage(session);
mailMessage.setFrom(new InternetAddress("example@example.com"));
mailMessage.setRecipients(Message.RecipientType.TO,InternetAddress.parse(mail.getTo()));
mailMessage.setSubject(mail.getSubject());
mailMessage.setText(mail.getMessage());
Transport.send(mailMessage);
只要我使用 ASCII 符号/字符,一切都有效.但是每当我想使用特定国家/地区"的字符时——比如 [õäöü]——我都会得到一堆看起来很奇怪的符号......
Everything works as long as I use ASCII symbols/ chars. But whenever I want to use "country-specific" characters - like [õäöü] - I get bunch of weird-looking symbols...
到目前为止我使用过的技术(对我不起作用):
Techniques I've used so far(which don't work for me):
setHeader("Content-Type", "text/plain; charset=UTF-8");
setHeader("Content-Encoding","ISO-8859-9");
setContent(message, "text/plain; charset=iso-8859-2");
注意:当执行 System.out.println() 以显示要发送的消息时,IDE 中的所有内容都会正确显示.
Note: everything is displayed correctly inside an IDE when System.out.println() is performed to display the message to be sent.
例如当发送的消息正文是 [õäöü]它在 Gmail 中显示为 [ä„"?].
e.x. when sent message body is [õäöü] It's displayed [ä„"?] in Gmail.
当使用 mailMessage.setText(MimeUtility.encodeText(mail.getMessage(), "UTF-8", "Q"));
时,Gmail 中的输出如下:
When mailMessage.setText(MimeUtility.encodeText(mail.getMessage(), "UTF-8", "Q"));
is used, then the output in Gmail is following:
"=?UTF-8?Q?=C3=A4=E2=80=9E=E2=80=9D=EF=BF=BD;=0D=0A?="
另一个有趣的是,当我这样做时:mailMessage.setText(strVar + "õäöü", "ISO-8859-1");
它实际上在我的电子邮件中很好地附加了õäöü"(但字符串的第一部分 [strVar] 仍然充满了 ? 和 []).
ANOTHER Interestingly, when I do: mailMessage.setText(strVar + "õäöü", "ISO-8859-1");
It actually appends "õäöü" nicely in my email (but the first part[strVar] of the string is still full of ?'s and []'s).
推荐答案
基本上,我的代码工作得很好,就像它应该的那样.是 cmd 无法处理非 ascii 字母.我使用 bat 文件来访问 jar.我想我只是要制作一个小图形用户界面……谢谢大家的回答.
Basically, my code works just fine, as its supposed to. It was the cmd, that could not handle non-ascii letters. I used a bat file to access a jar. I think I'm just going to make a little GUI then... Thanks everyone for answering.
这篇关于Java Mail API - 编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!