Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send combined plain text/HTML mail with Spring and JavaMail

I'm currently using JavaMail and Spring to send email in HTML. As it happens, the HTML is generated by some Velocity templates I have, and the sending code is roughly as follows:

MimeMessagePreparator preparator = new MimeMessagePreparator() {

    @Override public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");

            message.setSubject(msgInfo.getSubject());
            message.setFrom(msgInfo.getFrom());
            message.setReplyTo(msgInfo.getFrom());
            message.setTo(address);
            message.setText(someText, true);
    }
}

mailSender.send(preparator);

This works just fine, but it sends the mail with only a single part as text/html. What I need is to send it in multipart alternative with a plain text part. Is there a way, using Spring and JavaMail, to do this in an automatic way?


P.S.

In a former life when I programmed with Visual Basic and CDONTS this was built-in, but I can't seem to find a simple way to do it with Java. It's not terribly important that the plain text version look good, it just has to exist. What I'm trying to avoid is having to maintain a whole second set of Velocity templates just for this.

like image 975
Dan Avatar asked Sep 20 '11 20:09

Dan


1 Answers

In order to send both Text and HTML parts, you need to use a different setText() method:

public void setText(String plainText, String htmlText)

If you are setting the plain text to your HTML content, you may need to parse the HTML to remove the HTML tags.

like image 123
atrain Avatar answered Oct 21 '22 10:10

atrain