文件new1.txt包含作爲主題發送的UTF-8字符串。但收到的電子郵件將顯示CP1252格式的字符串。但是,如果我通過運行配置 - >常用選項卡並將控制檯編碼設置爲UTF-8來設置控制檯編碼,則可以在收到的電子郵件中正確查看UTF-string。我使用谷歌服務器爲這個測試:即使字符串爲UTF-8,電子郵件主題也會設置爲CP1252編碼
不工作: ℃〜¥æœ¬:合作伙伴名稱:??ã,¢ã,¹ãƒãƒ©ã,¼ãƒã,«æªå¼ä¼šç¤¾:
工作: 日本:合作伙伴名稱:アストラゼネカ株式會社
我的代碼: final String username =「[email protected]」; final String password =「xxxxxx」;
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
});
try {
File fileDir = new File("c:\\new1.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileDir), "UTF-8"));
String str;
String str1 ="";
while ((str = in.readLine()) != null) {
str1 += str;
}
Message message = new MimeMessage(session);
MimeMultipart mp = new MimeMultipart();
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject(str1);
MimeBodyPart body = new MimeBodyPart();
body.setContent("This is a Test EMail. Please ignore", "text/html");
body.setDisposition(MimeBodyPart.INLINE);
mp.addBodyPart(body);
byte[] attachmentData = str1.getBytes();
DataHandler dh = new DataHandler(new ByteArrayDataSource(attachmentData,"application/octet-stream"));
MimeBodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(dh);
attachment.setDisposition(MimeBodyPart.ATTACHMENT);
attachment.setFileName("new1.txt");
mp.addBodyPart(attachment);
message.setContent(mp);
Transport.send(message);
System.out.println("Done");
感謝 馬杜
以下是我在J2EE應用程序所做的代碼更改。在這裏它添加3個文件作爲附件。 3個文件之一是主題本身。在附件(Subject.txt)中,conent很好。
MimeMessage message = new MimeMessage(s);
....
message.setSubject(subject,"UTF-8");// MimeUtility.encodeText(subject,"UTF-8", "B"));
...
MimeBodyPart body = new MimeBodyPart();
body.setContent(sm.getMailBody(), "text/html; charset=UTF-8");
body.setDisposition(MimeBodyPart.INLINE);
mp.addBodyPart(body);
The debug message. I could not add it as text
感謝您的解決方案。此解決方案工作。但這是我的測試程序。此解決方案不適用於我的J2EE應用程序。在這個應用程序中,我使用sendmail作爲Aix中的郵件服務器,J2EE應用程序在WebSPhere Process Server 7.0上運行。 –
你能描述一下差異嗎?你可能想這樣設置props.put(「mail.debug」,「true」);並捕獲輸出並編輯你的問題 - 這將包含原始消息數據和破壞的編碼頭字段 – Jan
這是調試消息: –