Estoy tratando de enviar correos con código html adjunto, pero en el correo que mando pone el codigo tal cual en lugar de interpretarlo el navegador.
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP
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");
// autenticador
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creando el mensaje de e-mail
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
// enviando el e-mail
Transport.send(msg);
}
}
el metodo para mandar el email
public static void main(String[] args) {
String host = "smtp.mail.yahoo.com";
String port = "587";
String user = "**************";
String pass = "****";
String resultMessage = "";
String content = "<!DOCTYPE html>\n"
+ "<html>\n"
+ "<head>\n"
+ "<style>\n"
+ "table {\n"
+ " border-collapse: collapse;\n"
+ " width: 100%;\n"
+ "}\n"
+ "\n"
+ "th, td {\n"
+ " text-align: left;\n"
+ " padding: 8px;\n"
+ "}\n"
+ "\n"
+ "tr:nth-child(even){background-color: #f2f2f2}\n"
+ "\n"
+ "th {\n"
+ " background-color: #4CAF50;\n"
+ " color: white;\n"
+ "}\n"
+ "</style>\n"
+ "</head>\n"
+ "<body>\n"
+ "\n"
+ "<h2>Colored Table Header</h2>\n"
+ "\n"
+ "<table>\n"
+ " <tr>\n"
+ " <th>Firstname</th>\n"
+ " <th>Lastname</th>\n"
+ " <th>---------</th>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Peter</td>\n"
+ " <td>Griffin</td>\n"
+ " <td>$100</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Lois</td>\n"
+ " <td>Griffin</td>\n"
+ " <td>$150</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Joe</td>\n"
+ " <td>Swanson</td>\n"
+ " <td>$300</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Cleveland</td>\n"
+ " <td>Brown</td>\n"
+ " <td>$250</td>\n"
+ "</tr>\n"
+ "</table>\n"
+ "\n"
+ "</body>\n"
+ "</html>";
try {
EmailUtility.sendEmail(host, port, user, pass, email, subject,
content);
resultMessage = "el email fue enviado";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = " error: " + ex.getMessage();
} finally {
System.out.println("se envio el email");
}
}
si se envia el correo pero la estructura html llega como codigo tal cual no es interpretado
msg.setText(message);
. El métodosetText
tiene por defecto un tipo de contenidotext/plain
. Si quieres enviar contenido HTML puedes usar el métodosetContent
del siguiente modo:msg.setContent(message, "text/html; charset=utf-8");