简体   繁体   中英

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

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("emailBody") .

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!

带有土耳其语字符的Java邮件问题 ..可能此链接可以回答您的问题

" 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...)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM