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

我正在一个需要发送电子邮件的项目中工作。电子邮件已经发送完毕,但是我需要实现一种更专业的格式,根据我的研究,我可以将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,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(测试)。

stpab 回答:如何在JSP,Servlet应用程序中以html格式转换电子邮件的内容?

尽管您没有确切说明问题所在,但可能是在致电msg.setText(mensaje);之后再致电msg.setContent("<h1>Maipo Grande,lider en exportación</h1>","text/html");

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

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

有关javax.mail.MessagesetContent()的更多信息,请参见由类setText()实现的the Javadoc for the interface javax.mail.Part

另一个相关的观点是,您的EmailServicio.enviarEmail()方法几乎是教程“ JavaMail API - Sending an HTML Email”中类main()的{​​{1}}方法的直接副本,除了您添加的对SendHTMLEmail的呼叫之外。

值得验证您可以首先成功运行其简单Java应用程序的实现。如果有任何要解决的问题,调试Java应用程序比servlet容易得多。 HTML电子邮件应用程序正常工作后,您就可以将工作代码移植到Web应用程序上。

本文链接:https://www.f2er.com/3131205.html

大家都在问