使用JavaMail发送包含Unicode字符的邮件

Noo*_*z42 5 java unicode jakarta-mail

我使用以下代码成功通过GMail的SMTP服务器发送电子邮件:

        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");
        props.put("mail.smtp.ssl", "true");                 
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.timeout", "5000");             
        props.put("mail.smtp.connectiontimeout", "5000"); 

        // Do NOT use Session.getDefaultInstance but Session.getInstance
        // See: http://forums.sun.com/thread.jspa?threadID=5301696
        final Session session = Session.getInstance( props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication( USER, PWD );
                    }
                });

        try {
            final Message message = new MimeMessage(session);
            message.setFrom( new InternetAddress( USER ) );
            message.setRecipients( Message.RecipientType.TO, InternetAddress.parse( TO ) );
            message.setSubject( emailSubject );
            message.setText( emailContent );
            Transport.send(message);
            emailSent = true;
        } catch ( final MessagingException e ) {
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

其中emailContent是一个包含Unicode字符的String(如欧元符号).

当电子邮件到达时(在另一个GMail帐户中),欧元符号已转换为ASCII'?' 问号.

我对电子邮件了解不多:电子邮件可以使用任何字符编码吗?

我应该在上面的代码中修改什么,以便使用允许Unicode字符的编码?

Noo*_*z42 13

回答我自己的问题:你需要使用Message类中的setHeader方法,如下所示(以下内容已经尝试过并且正在运行):

message.setHeader("Content-Type", "text/plain; charset=UTF-8");
Run Code Online (Sandbox Code Playgroud)


bma*_*ies 4

您将需要指定内容类型的 MIME 标头来告诉它您要以 UTF-8 发送电子邮件。

使用 MimeMessage 并使用两个参数调用 setText,并传入字符集。