如何使用javamail发送包含unicode字符的电子邮件?

nnsrf1az  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(248)

我正在为重置密码页编写代码(使用jsp/servlet)。这是我的密码。
emailutility类

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)中看到的那样
请帮我修正这个错误,非常感谢!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题