我正在使用JAVA-MAIL API发送主题行包含用户名的用户邮件。对于任何英文字母名称,名称正确显示在主题行中(我使用message.setSubject()设置),但是当我输入中文名称时,它在主题行中没有正确反映。
相同的中文名称正好显示在我尝试使用setContent()显示这些捕获实体的正文部分中。我试图改变编码格式,但后来我得到了UnsupportedEncodingException错误。请帮助我如何在主题行中获得完全相同的名称(可能是英语/中文/日语)。
以下是我正在使用的代码:
public class RegistrationController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("fullname");
String Addr = request.getParameter("address");
String age = request.getParameter("age");
String Qual = request.getParameter("qual");
String Persent = request.getParameter("percent");
String Year = request.getParameter("yop");
if (name.isEmpty() || Addr.isEmpty() || age.isEmpty() || Qual.isEmpty()
|| Persent.isEmpty() || Year.isEmpty()) {
RequestDispatcher rd = request
.getRequestDispatcher("registration.jsp");
out.println("<font color=red>OOPS!! YOU MISSED OUT SOME FIELDS. FILL THEM AGAIN</font>");
rd.include(request, response);
} else {
try {
final String username = "abc@gmail.com";
final String password = "*****";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,
password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("abc@gmail.com"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("xyz@gmail.com"));
message.setSubject("THANK YOU " +name+ " FOR SUBSCRIBING WITH US!!");
message.setContent(
"<h3>Please review your entered details below.</h3><table><tr><td>Name</td><td>"
+ name
+ "</td></tr><tr><td>Address</td><td>"
+ Addr
+ "</td></tr><tr><td>Age</td><td>"
+ age
+ "</td></tr><tr><td>Qualification</td><td>"
+ Qual
+ "</td></tr><tr><td>Percentage</td><td>"
+ Persent
+ "</td></tr><tr><td>Passout</td><td>"
+ Year
+ "</td></tr></table>", "text/html");
Transport.send(message);
System.out.println("mail sent successful");
} catch (MessagingException ex) {
ex.printStackTrace();
} finally {
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
}
}
当我尝试下面的代码时,它抛出了UnsupportedEncodingException。
message.setSubject("THANK YOU " +new String(name.getBytes("UTF-8"))+ " FOR SUBSCRIBING WITH US!!");