开发者

Java mail vs. MySQL: probably a character encoding issue?

开发者 https://www.devze.com 2023-02-15 20:12 出处:网络
I\'m currently fetching data from a MySQL database using JDBC and executeQuery. One of the fields contains the email content, which I fetch via ResultSet.getString(\"email开发者_运维技巧Body\").

I'm currently fetching data from a MySQL database using JDBC and executeQuery. One of the fields contains the email content, which I fetch via ResultSet.getString("email开发者_运维技巧Body").

The mail is sent using the following code (simplified):

Properties props = new Properties();
Session session;
Message message;

props.put("mail.smtp.host", "mysmtpserver");
session = Session.getInstance(props, null);
message = new MimeMessage(session);

message.setFrom(new InternetAddress("myaddress@example.com", "System");
message.setSubject("Automatic notification");

message.setRecipient(RecipientType.BCC,
        new InternetAddress("admin@example.com", "Admin Distribution List"));
// email contains the previously fetched value
message.setContent(email, "text/plain"); 
Transport.send(message);

This works fine for all characters, including german umlaute, brackets, etc. Unfortunately the following characters fail:

– which is displayed as ? on the mail clients
" which becomes \"
' which is sent as \'

I couldn't find anything useful on the web, please advise. Many thanks!


Your mail is probably send encoded as iso-8859-1, which does not include the codepoint for en-dash. You could try to specify the charset as utf-8 in the setContent call:

message.setContent(email, "text/plain; charset=utf-8");

This does however not explain the problem with quotes you are seeing, but I guess these are actually two different problems.


" turing into \" and ' turining into \' is escaping issue. During insert those values were escaped so it won't break sql insert query. During select you have to unescape them. (don't know specific java functions...)


The quotes problem is happening because at some point the strings are being escaped one too many times.

If you select the strings from the database manually, does this return quotes visually escaped? If so, you're escaping too many times before inserting into the database.

0

精彩评论

暂无评论...
验证码 换一张
取 消