Java Mail is not supporting UTF-8 Characters in Subject of the email

前端 未结 1 629
-上瘾入骨i
-上瘾入骨i 2021-01-05 09:02

Here is my code of setting subject to the email:

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


        
相关标签:
1条回答
  • 2021-01-05 09:22

    The subject you mention here consists completely of ASCII characters. This includes the funny special characters ™. If you want it to be Unicode, just use Unicode and not the HTML-escaping. Mails don't have anything to do with HTML.

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

    This should encode the subject as something like =?UTF-8?Q?Your...subscription?=, as specified in RFC 2047.

    The complete example code:

    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);
      }
    }
    

    The output:

    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
    

    You can see that the subject header is encoded, and this is necessary and correct.

    [Update: I fixed the Unicode escape sequence, as indicated in one of my comments.]

    0 讨论(0)
提交回复
热议问题