如何在 JSP、Servlet 应用程序中将电子邮件的内容转换为 html 格式?

How to convert the content of email message in html format in JSP, Servlet aplication?

我正在从事一个需要发送电子邮件的项目。电子邮件已经在发送,但我需要实施更专业的格式,根据我的研究,我可以实施 HTML 格式来发送电子邮件。这是必要的,因为我必须放置与项目公司相关的信息(图片 公司的)。我尝试使用 msg.SendContent 但它对我不起作用。希望大家多多指教

我将 NetBeans 与 javax.mail 库一起使用:

public class EmailServicio {

    public static void enviarEmail(String host, String port,
            final String user, final String pass, String destinatario,
            String asunto, String mensaje) throws AddressException,
            MessagingException {

        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pass);
            }
        };

        Session session = Session.getInstance(properties, auth);

        // creates a new e-mail message
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(user));
        InternetAddress[] toAddresses = {new InternetAddress(destinatario)};
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(asunto);
        msg.setContent("<h1>Maipo Grande, lider en exportación</h1>", "text/html");
        msg.setSentDate(new Date());
        msg.setText(mensaje);

        // sends the e-mail
        Transport.send(msg);
    }
}

Servlet代码:

public class ServletContacto extends HttpServlet {

    private String host;
    private String port;
    private String user;
    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");
        user = context.getInitParameter("user");
        pass = context.getInitParameter("pass");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        UsuarioServicio usua = new UsuarioServicio();
        String url = request.getRequestURI();

        if ("/maipoGrande/Contacto".equals(url)) {
            request.setAttribute("titulo", "Formulario Contacto");
            HttpSession session = request.getSession(true);
            if (session.getAttribute("usuario") == null) {
                response.sendRedirect(request.getContextPath() + "/Login");
            } else {
                getServletContext().getRequestDispatcher("/contacto.jsp").forward(request, response);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String url = request.getRequestURI();
        if ("/maipoGrande/Contacto".equals(url)) {
            String destinatario = "atencion.maipogrande@gmail.com";
            String asunto = request.getParameter("txtAsunto");
            String mensaje = request.getParameter("txtMensaje");
            String mensajeRespuesta = "";
            try {
                EmailServicio.enviarEmail(host, port, user, pass, destinatario, asunto,
                        mensaje);
                mensajeRespuesta = "Su correo fue enviado exitosamente";
            } catch (Exception ex) {
                ex.printStackTrace();
                mensajeRespuesta = "Se ha encontrado un error: " + ex.getMessage();
            } finally {
                request.setAttribute("Mensaje", mensajeRespuesta);
                getServletContext().getRequestDispatcher("/resultado.jsp").forward(
                        request, response);
            }
        }
    }
}

希望发送的消息中显示h1(test)

虽然你没有说清楚你的问题是什么,但可能是你在调用msg.setContent("<h1>Maipo Grande, lider en exportación</h1>", "text/html");后又调用了msg.setText(mensaje);

您对 msg.setContent() 的调用会将 MIME 类型设置为 "text/html",这正是您想要的。但是随后调用 msg.setText() 会将 MIME 类型重置为 "text/plain",这不是您发送 HTML 电子邮件时想要的类型..

解决方案就是删除对 msg.setText() 的调用。然后您将发送一封 HTML 电子邮件。当然,您还需要为应用程序的电子邮件修改传递给 msg.setContent() 的消息内容,但这只是一个实现细节。

请参阅 the Javadoc for the interface javax.mail.Part,它由 class javax.mail.Message 实现,以获取有关 setContent()setText() 的更多信息。

另一个相关点是,看起来您的 EmailServicio.enviarEmail() 方法几乎是教程中 class SendHTMLEmailmain() 方法的直接副本“JavaMail API - Sending an HTML Email",除了对您添加的 setText() 的调用。

首先验证您是否可以成功 运行 实施他们简单的 Java 应用程序是值得的。如果有任何问题需要解决,调试 Java 应用程序比调试 servlet 容易得多。一旦您的 HTML 电子邮件应用程序开始工作,您就可以将您的工作代码移植到 Web 应用程序。