java - 如何使用 JavaMail 发送包含 UNICODE 字符的电子邮件?
问题描述
我正在为重置密码页面编写代码(使用 JSP/Servlet)。这是我的代码。
- 电子邮件实用程序类
public class EmailUtility {
public static void sendEmail(String host, String port, String socketFactoryClass, String auth,
final String senderEmail, String senderName, final String password,
String recipientEmail, String subject, String message) throws MessagingException, UnsupportedEncodingException {
//Get properties object
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", socketFactoryClass);
props.put("mail.smtp.auth", auth);
props.put("mail.smtp.port", port);
//Get Session
Authenticator authenticator = new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, password);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
//Create a new e-mail message
Message msg = new MimeMessage(session);
msg.setHeader("Content-Type", "text/plain; charset=UTF-8");
msg.setFrom(new InternetAddress(senderEmail, senderName));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
//Send the e-mail
Transport.send(msg);
}
}
- 我的 servlet 控制密码重置
@WebServlet(name = "ResetPasswordController", urlPatterns = {"/ResetPassword"})
public class ResetPasswordController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String host;
private String port;
private String socketFactoryClass;
private String auth;
private String email;
private String name;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
socketFactoryClass = context.getInitParameter("socketFactoryClass");
auth = context.getInitParameter("auth");
email = context.getInitParameter("email");
name = context.getInitParameter("name");
pass = context.getInitParameter("pass");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String recipient = request.getParameter("reset-email");
String subject = "Mật khẩu của bạn đã được đặt lại";
CustomerServices customerServices = new CustomerServices();
String newPassword = customerServices.resetCustomerPassword(recipient);
String content = "Xin chào, đây là mật khẩu mới của bạn đã được hệ thống tạo ra ngẫu nhiên: " + newPassword;
content += "\nChú ý: vì lí do bảo mật, bạn phải đổi mật khẩu ngay sau khi đăng nhập.";
content += "\nĐội ngũ hỗ trợ UNIFOOD";
String message = "";
try
{
EmailUtility.sendEmail(host, port, socketFactoryClass, auth, email, name, pass,
recipient, subject, content);
message = "Mật khẩu của bạn đã thay đổi, hãy kiểm tra email của bạn!";
}
catch (Exception ex)
{
ex.printStackTrace();
message = "Có lỗi xảy ra: " + ex.getMessage();
}
finally
{
request.setAttribute("message", message);
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String url = "/reset-password.jsp";
request.getRequestDispatcher(url).forward(request, response);
}
}
我遇到了一个问题,通过这种方式发送的所有电子邮件都不能包含所有 UNICODE 字符。一些字符被替换为?
,您可以在这张图片中看到EmailSent(1)
在上面的 EmailUtility 类中,我尝试msg.setHeader("Content-Type", "text/plain; charset=UTF-8");
按照此页面上的一篇文章的建议使用此命令修复此错误,但它不起作用。我也尝试使用setText()
带有两个参数的函数,setText(message, "UTF-8")
但没有setText()
函数需要 2 个参数。
然而,奇怪的是,当我main()
在类似于函数的 EmailUtility 类中编写sendEmail()
函数并在控制台中运行代码时,
public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {
String host = "smtp.gmail.com";
String port = "465";
String socketFactoryClass = "javax.net.ssl.SSLSocketFactory";
String auth = "true";
String senderEmail = "mySenderEmail";
String password = "myPassword";
String senderName = "UNIFOOD-SUPPORT";
String recipientEmail = "myRecipientEmail";
String subject = "Mật khẩu của bạn đã được đặt lại";
String message = "Xin chào, đây là mật khẩu mới của bạn đã được hệ thống tạo ra ngẫu nhiên: ";
message += "\nVì lí do bảo mật, bạn phải đổi mật khẩu ngay sau khi đăng nhập.";
message += "\nĐội ngũ hỗ trợ UNIFOOD";
//Get properties object
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", socketFactoryClass);
props.put("mail.smtp.auth", auth);
props.put("mail.smtp.port", port);
//Get Session
Authenticator authenticator = new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, password);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
//Create a new e-mail message
Message msg = new MimeMessage(session);
msg.setHeader("Content-Type", "text/plain; charset=UTF-8");
msg.setFrom(new InternetAddress(senderEmail, senderName));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
//Send the e-mail
Transport.send(msg);
System.out.println("Done");
}
我收到的电子邮件没有遗漏任何 UNICODE 字符,正如您在这张图片中看到的EmailSent(2)
请帮我解决这个错误,非常感谢!
解决方案
使用 msg.setContent(message, "text/html; charset=utf-8") 而不是 msg.setText(message);
推荐阅读
- ruby-on-rails - Rails 5 gem'delayed_job_active_record'未初始化的常量作业
- laravel - 在 null 上调用成员函数 checkLearning()(查看:
- c# - 统一按钮切换颜色
- r - 返回一个小标题:如何使用 case_when 进行矢量化?
- python - 这个 python for 循环实际上在做什么
- stata - 缩短变量的所有值标签
- mysql - 一对多关系如何在spring boot中保存数据
- android - Android:使用圆形锚定 FAB 向 BottomAppBar 添加圆角
- r - R不会删除命令中的所有行(但没有错误)
- c - C - scanf 在没有直接访问的情况下更改数组的值