我使用以下代码成功地通过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();
}
其中emailContent是包含Unicode字符(如欧元符号)的String。
当邮件到达(另一个GMail帐户时),欧元符号已被转换为ASCII“?”问号。
我对电子邮件不太了解:电子邮件可以使用任何字符编码吗?
我应该修改上面的代码以使用允许Unicode字符的编码?