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



我在一个需要发送电子邮件的项目中工作。电子邮件已经在发送,但我需要实现一种更专业的格式,根据我的研究,我可以实现电子邮件的HTML格式。这是必要的,因为我必须将与项目公司有关的信息(图片公司(。我试着用短信。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(测试(显示在发送的消息中。

虽然您还没有明确说明问题所在,但可能是在调用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()的消息的内容,但这只是一个实现细节。

有关setContent()setText()的更多信息,请参阅由类javax.mail.Message实现的接口javax.mail.Part的Javadoc。

另一个相关点是,除了您添加的对setText()的调用之外,您的EmailServicio.enviarEmail()方法几乎是教程"JavaMail API-发送HTML电子邮件"中SendHTMLEmail类的main()方法的直接副本。

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

最新更新