Reputation: 2970
I've already tried the charset suggestion at this link
But the email shows up with the exact value of messageText... not rendering any of the HTML.
Here is my current code
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
String messageText = "<br/>THIS IS A TEST...<br/>!!!";
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.ssl.enable", "true");
Session mailSession = Session.getInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(messageSubject);
message.setContent(messageText, "text/html; charset=utf-8");
Address[] fromAddress = InternetAddress.parse ( "pleasedonotreplymessage@[removed]" ) ;
message.addFrom( fromAddress );
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
transport.connect("[removed]", "", "");
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
I would prefer not to have to install other parties tools.. which would require a complete rework of my current code.
Upvotes: 3
Views: 4866
Reputation: 12114
You can use Thymeleaf to render rich HTML email and send it with Spring Mail utilities.
Tutorial: http://www.thymeleaf.org/doc/articles/springmail.html
Tutorial source code: https://github.com/thymeleaf/thymeleafexamples-springmail
Upvotes: 1
Reputation: 969
This is tested and confirmed to work.
There are more elegant structures to use for an HTML email that are supported by a wider array of email clients, but for a quick solution this works in the readers I've tested (Outlook, Android mail client connected to Exchange, and Gmail).
public static void sendHtmlEmail(String server, String from, String to, String cc, String subject, String htmlBody) throws MessagingException {
Properties props = new Properties();
props.setProperty("mail.smtp.host", server);
Session session = Session.getInstance(props);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(from);
msg.setRecipients(RecipientType.TO, to);
msg.setRecipients(RecipientType.CC, cc);
msg.setSubject(subject);
msg.setSentDate(new Date());
MimeMultipart mp = new MimeMultipart();
MimeBodyPart part = new MimeBodyPart();
part.setText(htmlBody);
mp.addBodyPart(part);
msg.setContent(mp);
// Content type has to be set after the message is put together
// Then saveChanges() must be called for it to take effect
part.setHeader("Content-Type", "text/html");
msg.saveChanges();
Transport.send(msg);
}
Upvotes: 2