gpt4 book ai didi

Java Mail 不支持电子邮件主题中的 UTF-8 字符

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:09:18 25 4
gpt4 key购买 nike

这是我设置邮件主题的代码:

  String bodyMessage="Dear Renavçilçleç Françoisç InCites™";
String subject = "Your new InCites™ subscription";

Properties _sessionProperties = new Properties();
_sessionProperties.put("mail.transport.protocol", "smtp");
_sessionProperties.put("mail.smtp.host", "hostname");
_sessionProperties.put("mail.smtp.port", "25");

Session session = Session.getInstance(_sessionProperties, null);

MimeMessage mimemsg = new MimeMessage(session);
mimemsg.addRecipients(Message.RecipientType.TO, "xxx@gmail.com");
mimemsg.setSubject(subject, "UTF-8");

// Create a multi-part message
MimeMultipart multipart = new MimeMultipart();
// Set the subType
multipart.setSubType("alternative");
BodyPart part = new MimeBodyPart();

part.setContent(bodyMessage, "charset=UTF-8");

// Set the emailBody and emailType to MIME BodyPart
part.setDataHandler(new DataHandler(new ByteArrayDataSource(
bodyMessage, "text/html;")));

// Add the MIME BodyPart to MIME multiPart
multipart.addBodyPart(part);

// Put parts in message
mimemsg.setContent(multipart);

// Send message
Transport.send(mimemsg);

但在电子邮件主题中它仍然显示为 “您的新 InCites™ 订阅”

最佳答案

你在这里提到的主题完全由ASCII字符组成。这包括有趣的特殊字符 。如果您希望它是 Unicode,只需使用 Unicode 而不是 HTML 转义。邮件与 HTML 无关。

mimemsg.setSubject("Your new InCites\u2122 subscription", "UTF-8");

这应该将主题编码为类似于 =?UTF-8?Q?Your...subscription?= 的形式,如 RFC 2047 中指定的那样.

完整示例代码:

package so4406538;

import java.io.IOException;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

public class MailDemo {

public static void main(String[] args) throws MessagingException, IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
message.setSubject("Your new InCites\u2122 subscription", "UTF-8");
message.setContent("hello", "text/plain");
message.writeTo(System.out);
}
}

输出:

Message-ID: <7888229.0.1291967222281.JavaMail.roland@bacc>
Subject: =?UTF-8?Q?Your_new_InCites=E2=84=A2_subscription?=
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

hello

您可以看到主题标题已编码,这是必要且正确的。

[更新:我修复了 Unicode 转义序列,如我的评论之一所示。]

关于Java Mail 不支持电子邮件主题中的 UTF-8 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4406538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com