Domanda

What I'm doing is an email template module. I can send successfully but when I read the sent mail the line-breaks disappeared for example this is what I sent:

"
Dear ñ ,


                     ABCDEFGHIJKLMNOPQRSTUVWXYZ. abcdefghijklmnopqrstuvwxyz. 1234567890. !@#$%^&*()_. Loren ipsum blahbity blahbity blah blah. WQWERTYUIOP{}ASDFGHJKL"ZXCVBNM<>


                   I am white spaces



"

This is what I received:

"Dear ñ , ABCDEFGHIJKLMNOPQRSTUVWXYZ. abcdefghijklmnopqrstuvwxyz. 1234567890. !@#$%^&*()_. Loren ipsum blahbity blahbity blah blah.QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<> I am white spaces"

Take note that the email body came body the database then stored into a pojo.

The test method for sending:

@Test
public void sendServiceTest() {
    String hostName = null;
    // Set up the SMTP server.
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", getHost);

    Session session = Session.getDefaultInstance(props);
    session.setDebug(true);

    Message msg = new MimeMessage(session);

    try {
        hostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        msg.setFrom(new InternetAddress(hostName));
        InternetAddress manyAddressTo = null;
        // InternetAddress[] manyAddressCC = null;
        // InternetAddress[] manyAddressBCC = null;
        List<EmailRecipient> recipients = emailRecipientService
                .selectRecipientByCode("E1");

        manyAddressTo = new InternetAddress("sample@sample.com");

        msg.setRecipient(Message.RecipientType.TO, manyAddressTo);
        msg.setSubject(recipients.get(0).getEmailTemplate().getSubject());

        msg.setContent(recipients.get(0).getEmailTemplate().getEmail_body()+"\r\n","text/html; charset=utf-8");
        Transport.send(msg);

    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
È stato utile?

Soluzione

Since you're using html content, you need to use html markup to control the formatting. Just putting in line breaks and whitespace isn't going to do it unless you're willing to use text/plain instead of text/html.

Altri suggerimenti

Consider formatting your email as HTML. It sure shot way of maintaining the formatting. Also, you could use the Commons Email library which will remove a lot of the boiler plate code you need to write.

Take a look at this

http://commons.apache.org/proper/commons-email/userguide.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top