Unicode chars and Spring JavaMailSenderImpl, no unicode chars under Linux!

前端 未结 3 1767
谎友^
谎友^ 2021-01-12 11:33

I\'m using Spring and JavaMailSenderImpl, a famous spring class to send emails. My emails contain a lot of unicode chars like èéàò or most notably the dreaded € symbol. My c

相关标签:
3条回答
  • 2021-01-12 12:27

    I am posting the solution.

    First make sure about the encoding of the source code (if there is inline text). In eclipse is the first screen if you choose project properties. Warning: if you change it later it will garble your text.

    Second It is better to use MimeMailMessage so that you can specify the encoding, like this:

    MimeMessage msg = mailSender.createMimeMessage();
    
            msg.addRecipient(RecipientType.TO, new InternetAddress(adminEmail));
            msg.addFrom(new InternetAddress[] { new InternetAddress(adminEmail) });
    
            msg.setSubject(subject, "UTF-8");
            msg.setText(message, "UTF-8");  
            mailSender.send(msg);
    

    Third make sure the system property mail.mime.charset is set to UTF-8, either from Java command or by code like this:

    System.setProperty("mail.mime.charset", "utf8");
    

    Thanks to everybody that helped me sorting this out.

    0 讨论(0)
  • 2021-01-12 12:29

    The problem is likely to be when you translate between an array of bytes (e.g. reading from a file) and a java.lang.String. Can you give more detail on your application's architecture?

    0 讨论(0)
  • 2021-01-12 12:30

    In my case, I resolved the encoding problem by specifying JavaMailSenderImpl's defaultEncoding:

    mailSender = new JavaMailSenderImpl();
    ...
    mailSender.setDefaultEncoding("UTF-8");
    

    I believe you can also set the value in bean configuration:

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        ...
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
    
    0 讨论(0)
提交回复
热议问题